Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn asynchronous calls into synchronous

Is there any good practice (pattern) in turning asynchronous calls into synchronous?
I have a third party library who's methods are all asynchronos, to get result of almoust any method you must listen to an event, which will bring some context with it. basically it looks like:

service.BeginSomething(...);
service.OnBeginSomethingCompleted += ;

what I need is to execute some code after BeginSomething when it is really complete (thus after OnBeginSomethingCompleted is triggered). It is very inconvinient to handle the response in the event.

The only way I could think of is running a Thread.Sleep loop and wait till some field on the form is updated, but it doesn't look like very elegant sollution.

I'm using .net 4.0.

like image 322
Georgy Smirnov Avatar asked Apr 12 '12 13:04

Georgy Smirnov


1 Answers

You could subclass the main class and provide a synchronous version of the operation. If subclassing is not an option you could create an extension method. Here is how things might look.

public class Subclass : BaseClass
{
  public void Something()
  {
    using (var complete = new ManualResetEventSlim(false))
    {
      EventHandler handler = (sender, args) => { complete.Set(); };
      base.OnBeginSomethingCompleted += handler;
      try
      {
        base.BeginSomething();
        complete.Wait();
      }
      finally
      {
        base.OnBeginSomethingCompleted -= handler;
      }
    }
  }
}

Update:

One thing I should have pointed out is that this could be problematic in some cases. Consider this example.

var x = new Subclass();
x.BeginSomething();
x.Something();

It should be obvious that the handler in Something could receive the OnBeginSomethingCompleted event from the previous call to BeginSomething. Make sure you guard against this somehow.

like image 196
Brian Gideon Avatar answered Sep 18 '22 16:09

Brian Gideon