我试图同步一个异步调用。
常规(async)流程如下所示:
- 使用 telnet 向服务器询问数据:'Session.sendToTarget(message)'
- 该应用程序继续做其他事情....
- 当服务器应答准备好时,服务器发送结果。
- 应用程序获取结果并引发事件“OnDataReceived”
来自服务器的数据对于下一步至关重要,所以我想保留一切,直到收到。
同步流程应如下所示:
- 向服务器请求数据:Session.sendToTarget(message)
- 等到从服务器收到数据
使用 c#,我尝试将操作与“WaitHandle.WaitOne(TimeToWaitForCallback)”同步,但未成功,似乎 WaitOne 暂停了应用程序以接收传入消息(我也尝试过在其他线程中等待)。在 TimeToWaitForCallback 时间过去后,我收到了对 WaitOne 操作停止的传入消息。
我尝试使代码同步:
public virtual TReturn Execute(string message)
{
WaitHandle = new ManualResetEvent(false);
var action = new Action(() =>
{
BeginOpertaion(message);
WaitHandle.WaitOne(TimeToWaitForCallback);
if (!IsOpertaionDone)
OnOpertaionTimeout();
});
action.DynamicInvoke(null);
return ReturnValue;
}
传入引发此代码:
protecte protected void EndOperation(TReturn returnValue)
{
ReturnValue = returnValue;
IsOpertaionDone = true;
WaitHandle.Set();
}
有任何想法吗?