gpt4 book ai didi

c# - 为什么这个 AsyncCallback 测试有时会失败?

转载 作者:太空狗 更新时间:2023-10-30 00:56:26 24 4
gpt4 key购买 nike

我有以下类试图充当简单的异步操作:

public class AsyncLineWriter
{
private delegate void SynchronousWriteLineDelegate(string message);
private SynchronousWriteLineDelegate DoWriteLine;
private void SynchronousWriteLine(string message)
{
Console.WriteLine(message);
}
public AsyncLineWriter()
{
DoWriteLine = new SynchronousWriteLineDelegate(SynchronousWriteLine);

public IAsyncResult BeginWriteLine(string message, AsyncCallback callback, object state)
{
return DoWriteLine.BeginInvoke(message,callback,state);
}
public void EndWriteLine(IAsyncResult asyncResult)
{
DoWriteLine.EndInvoke(asyncResult);
}
}

以下单元测试间歇性失败,但我不明白竞争条件在哪里:

[TestMethod]
public void Callback_is_called()
{
// Arrange
AsyncLineWriter lineWriter = new AsyncLineWriter();
object state = new object();
object callbackState = null;
AsyncCallback callback = (r) =>
{
callbackState = r.AsyncState;
};

// Act
IAsyncResult asyncResult = lineWriter.BeginWriteLine("test", callback, state);
lineWriter.EndWriteLine(asyncResult);

// Assert
Assert.AreSame(state, callbackState);
}

最佳答案

在此模式中,回调在线程池线程上运行,您应该从回调中调用 EndInvoke

EndInvoke 不等待回调完成(因为这会导致死锁),因此您在回调和测试方法之间进行竞争。


编辑:WAITING句柄也可以在回调完成之前设置。试试这个:

[TestMethod]
public void Callback_is_called()
{
// Arrange
var lw = new AsyncLineWriter();

object state = new object();
object callbackState = null;

var mre = new ManualResetEvent( false );

AsyncCallback callback = r =>
{
callbackState = r.AsyncState;

lw.EndWriteLine( r );

mre.Set();
};

// Act
var ar = lw.BeginWriteLine( "test", callback, state );
mre.WaitOne();

// Assert
Assert.AreSame( state, callbackState );
}

关于c# - 为什么这个 AsyncCallback 测试有时会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7756524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com