2010-12-10 229 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