Don't poll. Use the built-in synchronization facilities.
Up vote 2 down vote favorite share g+ share fb share tw.
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 response = null; bool executedCallBack = false; client. ExecuteAsync(request, (RestResponse aSyncResponse)=>{ executedCallBack = true; response = aSyncResponse; }); while (!executedCallBack){ Thread. Sleep(100); } ..continue execution synchronously c# multithreading asynchronous link|improve this question edited Jan 22 '11 at 17:28chibacity17.1k32250 asked Jan 22 '11 at 17:05Chris Kooken6,5702931 88% accept rate.
Don't poll. Use the built-in synchronization facilities. RestResponse response = null; var executedCallBack = new AutoResetEvent(false); client.
ExecuteAsync(request, (RestResponse 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.
No, I do not get an IAsyncResult. Whats the difference between ManualResetEvent and AutoResetEvent below? – Chris Kooken Jan 22 '11 at 17:45 1 For one-shot use, there is no difference.
A ManualResetEvent remains in the "set" state until you call Reset(), whereas an AutoResetEvent automatically resets after unblocking one waiting thread. Usually this is what you want. I only use ManualResetEvents when I specifically want to allow multiple waiting threads (or successive waits by the same thread) to be released.
– P Daddy Jan 22 '11 at 18:20.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.