如何取消可观察的序列 [英] How to cancel an observable sequence

查看:68
本文介绍了如何取消可观察的序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的 IObservable< int> ,它每500毫秒充当一次脉冲发生器:

I have a very simple IObservable<int> that acts as a pulse generator every 500ms:

var pulses = Observable.GenerateWithTime(0, i => true, i => i + 1, i => i,
                                         i => TimeSpan.FromMilliseconds(500))

我有一个 CancellationTokenSource (用于取消同时进行的其他工作).

And I have a CancellationTokenSource (that is used to cancel other work that is going on simultaneously).

如何使用取消令牌来源来取消我的可观察序列?

How can I use the cancellation token source to cancel my observable sequence?

推荐答案

如果您使用的是GenerateWithTime(现在已替换为Generate并传递了时间跨度函数重载),则可以替换第二个参数以评估取消状态令牌如下:

If you're using the GenerateWithTime (replaced now with Generate passing in a timespan func overload), you can replace the second parameter to evaulate the state of the cancellation token as follows:

var pulses = Observable.Generate(0,
    i => !ts.IsCancellationRequested,
    i => i + 1,
    i => i,
    i => TimeSpan.FromMilliseconds(500));

或者,如果可以将导致设置取消令牌的事件转换为可观察的事件,则可以使用以下内容:

Alternatively, if your event which causes the cancellation token to be set can be converted to an observable itself, you could use something like the following:

pulses.TakeUntil(CancelRequested);

我在 http:/上发布了更详细的解释./www.thinqlinq.com/Post.aspx/Title/Cancelling-a-Reactive-Extensions-Observable .

这篇关于如何取消可观察的序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆