C#同步进行异步调用
问题描述:
我有一个只允许异步调用的库,我的代码需要同步。下面的代码能正确工作吗?任何人都可以预见到它的任何问题?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
答
请勿投票。使用内置的同步功能。
RestResponse<T> response = null;
var executedCallBack = new AutoResetEvent(false);
client.ExecuteAsync(request, (RestResponse<T> aSyncResponse)=>{
response = aSyncResponse;
executedCallBack.Set();
});
executedCallBack.WaitOne();
//continue execution synchronously
作为一个方面说明,我不得不切换回调中的操作顺序。你的例子有一个竞争条件,因为该标志可以允许主线程继续,并尝试在回调线程写入之前读取响应。
答
通常异步调用返回你某种令牌(例如IAsyncResult),它可以让你只需静静等待,无需投票。你的API不会那么做吗?
另一种选择是使用ManualResetEvent
或Monitor.Wait
/Pulse
而不是睡眠循环。
不,我没有得到IAsyncResult。下面的ManualResetEvent和AutoResetEvent有什么区别? – 2011-01-22 17:45:37