Reputation: 22389
I have an asynchronous class with a StartProcessing()
method, that raises an int ResultReady()
event when it has finished processing. StartProcessing()
takes very little time.
I want to call this class synchronously. My pseudo-code should be something like:
Call StartProcessing()
Wait/sleep until result is ready
Return result
What design pattern is best for this? Can you please point me to a code example?
Upvotes: 4
Views: 3958
Reputation: 1503220
One simple way of doing this is with a ManualResetEvent
which the event handler and the waiting code both have access to. Call Set
from the event handler, and WaitOne
(or an overload with a timeout) from the waiting thread. Note that this can't be done on an STA thread, so you can't do it within a WinForms thread (which should always be STA) - but you shouldn't be waiting within a UI thread anyway.
Something like this:
var async = new AsyncClass();
var manualEvent = new ManualResetEvent();
async.ResultReady += args => manualEvent.Set();
async.StartProcessing();
manualEvent.WaitOne();
Upvotes: 6