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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With