Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Making an Async Call Synchronously

I have a library that only allows for Async calls, my code needs to be synchronous. Will the following code work correctly? Can anyone foresee any problems with it?

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
like image 650
Chris Kooken Avatar asked Dec 28 '22 02:12

Chris Kooken


2 Answers

Don't poll. Use the built-in synchronization facilities.

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

executedCallBack.WaitOne();
//continue execution synchronously

As a side note, I had to switch the order of operations inside the callback. Your example had a race condition, since the flag could allow the main thread to continue, and try to read the response, before the callback thread had written it.

like image 108
P Daddy Avatar answered Jan 08 '23 09:01

P Daddy


Usually async calls return you some sort of token (e.g. IAsyncResult) which lets you just wait for it, without polling. Does your API not do that at all?

Another option is to use ManualResetEvent or Monitor.Wait/Pulse instead of the sleep loop.

like image 27
Jon Skeet Avatar answered Jan 08 '23 08:01

Jon Skeet