Chris Kooken
Chris Kooken

Reputation: 33938

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

Upvotes: 4

Views: 3631

Answers (2)

P Daddy
P Daddy

Reputation: 29537

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.

Upvotes: 8

Jon Skeet
Jon Skeet

Reputation: 1503280

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.

Upvotes: 2

Related Questions