4

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?

Ilya Kogan
  • 21,995
  • 15
  • 85
  • 141

1 Answers1

6

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();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • When I do this it seems that ResultReady is never called. I suspect that the delegate is set to start in the same thread which is blocked. However the delegate in my case is called from a framework that I do not have control of. Hence I never get pass WaitOne. Do you have any ideas on how to solve it? – dynamokaj Oct 02 '15 at 07:35
  • @dynamokaj: Delegates aren't "set to start" in any particular thread. The framework you're using may decide to raise an event in a particular thread... but basically we can't help you without more information. I suggest you ask a new question with more details. – Jon Skeet Oct 02 '15 at 07:36