C#同步进行异步调用

C#同步进行异步调用,c#,multithreading,asynchronous,C#,Multithreading,Asynchronous,我有一个只允许异步调用的库,我的代码需要同步。以下代码是否正常工作?有人能预见到它会有什么问题吗 RestResponse<T> response = null; bool executedCallBack = false; client.ExecuteAsync(request, (RestResponse<T> aSyncResponse)=>{ executedCallBack = true; response = aSyncResponse;

我有一个只允许异步调用的库,我的代码需要同步。以下代码是否正常工作?有人能预见到它会有什么问题吗

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
response response=null;
bool executedCallBack=false;
client.ExecuteAsync(请求,(RestResponse aSyncResponse)=>{
executedCallBack=true;
响应=异步响应;
});
而(!executedCallBack){
睡眠(100);
}
..同步继续执行

通常异步调用会返回某种令牌(例如),让您只需等待,而无需轮询。你的API根本就不这样做吗


另一个选项是使用
手动重置事件
监视器。等待
/
脉冲
,而不是睡眠循环。

不轮询。使用内置的同步工具

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

executedCallBack.WaitOne();
//continue execution synchronously
response response=null;
var executedCallBack=new AutoResetEvent(false);
client.ExecuteAsync(请求,(RestResponse aSyncResponse)=>{
响应=异步响应;
executedCallBack.Set();
});
executedCallBack.WaitOne();
//同步继续执行

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

否,我没有得到IAsyncResult。下面的ManualResetEvent和AutoResetEvent之间有什么区别?对于一次性使用,没有区别。
ManualResetEvent
将保持“设置”状态,直到调用
Reset()
,而
AutoResetEvent
在解除阻塞一个等待线程后自动重置。通常这就是你想要的。仅当我特别希望释放多个等待线程(或同一线程的连续等待)时,才使用
ManualResetEvent
s。