4

我试图同步一个异步调用。

常规(async)流程如下所示:

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

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

同步流程应如下所示:

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

有任何想法吗?

4

3 回答 3

2
    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:我喜欢线程而不是动作符号:P

于 2010-12-10T12:06:57.997 回答
0

在这种情况下,ManualResetEvent 可以真正帮助您。

http://www.java2s.com/Tutorial/CSharp/0420__Thread/Useamanualeventobject.htm

于 2010-12-10T08:53:47.800 回答
0

下面的行

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

   Asking the server for data using telnet: 'Session.sendToTarget(message)' 
   The app move on doing other things.... 
   When the server answer ready, the server send the result. 
   The app get the result and raise event "OnDataReceived" 

并做到以下几点

Asking the server for data: Session.sendToTarget(message) 
Wait until the data received from the server 

它与阻塞请求一样好,所以只需同步调用 Session.sendToTarget(message) 即可。没有必要让它异步

于 2010-12-10T08:58:30.337 回答