简体   繁体   中英

ManualResetEvent to IObservable<bool> (or WaitHandle to IObservable<Unit> )?

I'd like to create an IObservable-stream based on Sets/Resets of a ManualResetEvent, eg 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 (eg 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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM