Chr*_*ken 4 c# multithreading asynchronous
我有一个只允许异步调用的库,我的代码需要同步.以下代码是否可以正常工作?任何人都可以预见到它的任何问题吗?
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
Run Code Online (Sandbox Code Playgroud)
不要民意调查.使用内置同步功能.
RestResponse<T> response = null;
var executedCallBack = new AutoResetEvent(false);
client.ExecuteAsync(request, (RestResponse<T> aSyncResponse)=>{
response = aSyncResponse;
executedCallBack.Set();
});
executedCallBack.WaitOne();
//continue execution synchronously
Run Code Online (Sandbox Code Playgroud)
作为旁注,我不得不在回调中切换操作的顺序.您的示例有一个竞争条件,因为该标志可以允许主线程继续,并尝试在回调线程写入之前读取响应.