我有一个只允许异步调用的库,我的代码需要同步。下面的代码能正常工作吗?任何人都可以预见它的任何问题吗?

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

作为旁注,我不得不在回调中切换操作顺序。您的示例存在竞争条件,因为该标志可以允许主线程继续,并在回调线程写入响应之前尝试读取响应。

关于C# 同步进行异步调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4769228/

10-10 19:25