[英]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 我想基于ManualResetEvent的Sets / Resets创建一个IObservable流,例如原则上类似
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. 当然,只有ManualResetEvent不会公开此类事件。 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. 作为记录,如果不可能在设置/取消设置为true / false之间进行区分,那么只要ManualResetEvent的状态更改也可以使用更简单的IObservable <Unit>推送值。
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). 我找到了一篇帖子,解释了如何将ManualResetEvent(或更确切地说,通常是一个WaitHandle)转换为任务( 将ManualResetEvent包装为等待的任务 ),该任务似乎在下一次ManualResetEvent更改(从设置为未设置)时完成,或其他方式)。 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());
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.