2011-01-22 170 views
4

我有一個只允許異步調用的庫,我的代碼需要同步。下面的代碼能正確工作嗎?任何人都可以預見到它的任何問題?C#同步進行異步調用

RestResponse<T> response = null; 
bool executedCallBack = false; 
client.ExecuteAsync(request, (RestResponse<T> aSyncResponse)=>{ 
    executedCallBack = true; 
    response = aSyncResponse; 
}); 

while (!executedCallBack){ 
    Thread.Sleep(100); 
} 
..continue execution synchronously 

回答

8

請勿投票。使用內置的同步功能。

RestResponse<T> response = null; 
var executedCallBack = new AutoResetEvent(false); 
client.ExecuteAsync(request, (RestResponse<T> aSyncResponse)=>{ 
    response = aSyncResponse; 
    executedCallBack.Set(); 
}); 

executedCallBack.WaitOne(); 
//continue execution synchronously 

作爲一個方面說明,我不得不切換回調中的操作順序。你的例子有一個競爭條件,因爲該標誌可以允許主線程繼續,並嘗試在回調線程寫入之前讀取響應。

2

通常異步調用返回你某種令牌(例如IAsyncResult),它可以讓你只需靜靜等待,無需投票。你的API不會那麼做嗎?

另一種選擇是使用ManualResetEventMonitor.Wait/Pulse而不是睡眠循環。

+0

不,我沒有得到IAsyncResult。下面的ManualResetEvent和AutoResetEvent有什麼區別? – 2011-01-22 17:45:37