Wait until a delegate is called

3.8k views Asked by At

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:

  1. Call StartProcessing()

  2. Wait/sleep until result is ready

  3. Return result

What design pattern is best for this? Can you please point me to a code example?

1

There are 1 answers

2
Jon Skeet On BEST ANSWER

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();