gpt4 book ai didi

c# - 使异步调用同步

转载 作者:行者123 更新时间:2023-11-30 12:35:55 24 4
gpt4 key购买 nike

我正在尝试同步一个异步调用。

常规(异步)流程如下所示:

  1. 使用 telnet 向服务器请求数据:'Session.sendToTarget(message)'
  2. 应用继续做其他事情....
  3. 当服务器回答准备好后,服务器发送结果。
  4. 应用获取结果并引发事件“OnDataReceived”

来自服务器的数据对下一步至关重要,所以我想保留一切直到收到。

sync 流程应该如下所示:

  1. 向服务器请求数据:Session.sendToTarget(message)
  2. 等到服务器收到数据

使用 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();
}

有什么想法吗?

最佳答案

    AutoResetEvent mutex = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
{
Thread.Sleep(2000);
Console.WriteLine("sleep over");
mutex.Set();
}));
mutex.WaitOne();
Console.WriteLine("done");
Console.ReadKey();

当异步操作完成时,将 mutex.Set() 放置到您的事件处理程序中...

ps:我喜欢thread over action notation :P

关于c# - 使异步调用同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4406994/

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