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?
One simple way of doing this is with a
ManualResetEvent
which the event handler and the waiting code both have access to. CallSet
from the event handler, andWaitOne
(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: