簡體   English   中英

可觀察的取消令牌

[英]Cancellation token for observable

如果在StartButton單擊上創建以下可觀察對象,即從停止按鈕創建,則如何取消以下類型的Rx Observable。

var instance = ThreadPoolScheduler.Instance; 

Observable.Interval(TimeSpan.FromSeconds(2), instance)
                     .Subscribe(_ =>
                     {
                     Console.WriteLine(DateTime.Now); // dummy event
                     }
                     );         

保留Subscribe返回的IDisposable ,並在其上調用Dispose

可能有一種方法可以將基於Rx IDisposable的取消訂閱與CancellationToken開箱即用,但只是調用Dispose將是一個開始。 (您可以隨時注冊一個帶取消令牌的續約來調用dispose ...)

這是一個簡短但完整的示例來演示:

using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        var instance = ThreadPoolScheduler.Instance;
        var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

        var disposable = Observable
            .Interval(TimeSpan.FromSeconds(0.5), instance)
            .Subscribe(_ => Console.WriteLine(DateTime.UtcNow));
        cts.Token.Register(() => disposable.Dispose());
        Thread.Sleep(10000);
    }
}

只需使用帶有CancellationTokenSubscribe的重載之一:

observable.Subscribe(_ => Console.WriteLine(DateTime.UtcNow), cancellationToken);

這簡化了Jon Skeet的例子:

using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        var instance = ThreadPoolScheduler.Instance;
        var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

        Observable.Interval(TimeSpan.FromSeconds(0.5), instance)
            .Subscribe(_ => Console.WriteLine(DateTime.UtcNow), cts.Token);
        Thread.Sleep(10000);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM