0

I'd like to create an IObservable-stream based on Sets/Resets of a ManualResetEvent, e.g. in principle something like

IObservable<bool> ToObservable(ManualResetEvent ev)
{
  var s = new Subject<bool>();
  ev.OnSet += s.OnNext(true);
  ev.OnReset += s.OnNext(false);
  return s;
}

Only that ManualResetEvent doesn't expose such events of course. So is there any way to observe when this gets stopped/reset?

For the record, if the differentiation between set/unset into true/false isn't possible, a more simple IObservable<Unit> pushing a value whenever the state of ManualResetEvent changes would be okay as well.

Is there any way of doing this?

I've found a post explaining how to convert a ManualResetEvent (or rather, a WaitHandle in general) into a task ( Wrapping ManualResetEvent as awaitable task ), which seems to complete whenever the next time is that the ManualResetEvent changes (from set to unset, or other way around). But I haven't really found any way how I could chain this up into a sequence (e.g. after the task completes, I'd need to create another one for the next event, etc., and somehow create an observable out of this "recursive" sequence)

Thanks!

Bogey
  • 4,926
  • 4
  • 32
  • 57

1 Answers1

0

There are many different ways to do this, but something likes this:

public static class ManualResetEventObservable
{
    public static IObservable<bool> Create(ManualResetEvent e, TimeSpan timeout)
    {
        return Observable.Create<bool>(observer =>
        {
            var cancelEvent = new ManualResetEvent(false);
            var waitHandles = new[] { cancelEvent, e };
            var thread = new Thread(new ThreadStart(() =>
            {
                var index = WaitHandle.WaitAny(waitHandles, timeout);
                if (index == 1)
                    observer.OnNext(true);

                observer.OnCompleted();
            }));
            thread.Start();
            return Disposable.Create(() => cancelEvent.Set());
        });
    }
Per
  • 1,061
  • 7
  • 11