C # Sync asynchronous call

I have a library that only allows Async calls, my code should be synchronous. Will the following code work correctly? Can anyone anticipate any problems with him?

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 
+4
source share
2 answers

Do not conduct a survey. Use the built-in synchronization tools.

 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. In your example, there was a race condition, since the flag could allow the main thread to continue and try to read the answer before the callback thread wrote it.

+8
source

Typically, asynchronous calls return some kind of token (for example, IAsyncResult ), which allows you to simply wait for it, without polling. Does your API not do this at all?

Another option is to use ManualResetEvent or Monitor.Wait / Pulse instead of a wait loop.

+2
source

Source: https://habr.com/ru/post/1336604/


All Articles