2010-12-10 226 views
4

我试图同步异步调用。使异步调用同步

常规(异步)流量的样子:

  1. 问计使用telnet数据的服务器: 'Session.sendToTarget(消息)'
  2. 在做其他事情的应用程序移动...
  3. 当服务器应答就绪时,服务器发送结果。
  4. 的应用程序得到的结果,提高事件“OnDataReceived”

的数据从服务器是为下一步所以我想,直到它的接收来保存所有的关键。

同步流应该是这样的:

  1. 问计数据的服务器:Session.sendToTarget(消息)
  2. 等待,直到从服务器

接收到的数据使用C# ,我尝试将操作与'WaitHandle.WaitOne(TimeToWaitForCallback)'同步失败,似乎WaitOne暂停接收传入消息的应用程序(我试过以及等待其他人)。 Afther 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(); 
     } 

任何想法?

+0

当然'WaitHandler。WaitOne'阻止当前线程并等待任务,直到处理程序发出信号。这不是你想要的吗?你说你想要“等到从服务器收到数据”。 – 2010-12-10 08:41:19

+0

是的,我想等,但阻止阻止我的应用程序获取服务器传入的消息,所以处理程序从不发送信号,它停止等待超时。 – 2010-12-10 11:56:48

回答

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(消息)即可。使得它的无点异步

+0

我无法同步调用它。我无法控制这个会话,以及它如何调用它的服务器调用。 – 2010-12-10 11:59:50

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()的异步opperation完成时,你的事件处理程序...

PS:我喜欢在动作符号螺纹:P

+0

当服务器发回(在新会话中)结果时,而不是在第一个操作完成时,异步操作完成。 – 2010-12-10 12:30:39

+0

你得到一个事件,对吧?所以调用者的WaitOne()和设置在事件处理程序中。假设“新会话”也是一个新线程。否则,你必须将整个事件封装在工作线程中并等待完成(例如Thread.Join) – Jaster 2010-12-10 12:36:35