Using Rx to synchronize asynchronous events

Posted by Martin Liversage on Stack Overflow See other posts from Stack Overflow or by Martin Liversage
Published on 2010-06-02T08:54:06Z Indexed on 2010/06/03 1:14 UTC
Read the original article Hit count: 361

Filed under:
|
|
|

I want to put Reactive Extensions for .NET (Rx) to good use and would like to get some input on doing some basic tasks. To illustrate what I'm trying to do I have a contrived example where I have an external component with asyncronous events:

class Component {

  public void BeginStart() { ... }

  public event EventHandler Started;

}

The component is started by calling BeginStart(). This method returns immediately, and later, when the component has completed startup, the Started event fires.

I want to create a synchronous start method by wrapping the component and wait until the Started event is fired. This is what I've come up with so far:

class ComponentWrapper {

  readonly Component component = new Component();

  void StartComponent() {
    var componentStarted =
      Observable.FromEvent<EventArgs>(this.component, "Started");
    using (var startedEvent = new ManualResetEvent(false))
      using (componentStarted.Take(1).Subscribe(e => { startedEvent.Set(); })) {
        this.componenet.BeginStart();
        startedEvent.WaitOne();
      }
  }

}

I would like to get rid of the ManualResetEvent, and I expect that Rx has a solution. But how?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET