C# 如何允许使用.NET 4中Rx的isScheduler.SchedulePeriodic方法取消正在运行的工作

C# 如何允许使用.NET 4中Rx的isScheduler.SchedulePeriodic方法取消正在运行的工作,c#,.net-4.0,system.reactive,C#,.net 4.0,System.reactive,我想使用Rx中的isScheduler.SchedulePeriodic方法定期运行一些工作。我希望不仅能够在执行之间取消工作,而且还能够在工作运行时(协同地)取消工作,方法是允许工作接受CancellationToken,该令牌在处理SchedulePeriodic返回的IDisposable时被取消 IDisposable的处理不应阻止,直到工作被取消,只需为工作提供在下一次机会取消自身的机会 如何使用.NET 4.0中的Rx实现这一点 看起来(请参阅“使调度程序更易于与'wait'一起使用

我想使用Rx中的isScheduler.SchedulePeriodic方法定期运行一些工作。我希望不仅能够在执行之间取消工作,而且还能够在工作运行时(协同地)取消工作,方法是允许工作接受
CancellationToken
,该令牌在处理SchedulePeriodic返回的IDisposable时被取消

IDisposable的处理不应阻止,直到工作被取消,只需为工作提供在下一次机会取消自身的机会

如何使用.NET 4.0中的Rx实现这一点


看起来(请参阅“使调度程序更易于与'wait'一起使用”一节)可以帮助实现这一点,但它在.NET 4中不可用。

这是我提出的扩展方法:

public static IDisposable SchedulePeriodic(
    this IScheduler scheduler,
    TimeSpan interval,
    Action<CancellationToken> work) {

    if (scheduler == null) {
        throw new ArgumentNullException("scheduler");
    }
    if (work == null) {
        throw new ArgumentNullException("work");
    }

    var cancellationDisposable = new CancellationDisposable();

    var subscription = scheduler.SchedulePeriodic(
        interval,
        () => {
            try {
                work(cancellationDisposable.Token);
            } catch (OperationCanceledException e) {
                if (e.CancellationToken != cancellationDisposable.Token) {
                    // Something other than the token we passed in threw this exception
                    throw;
                }
            }
        });

    return new CompositeDisposable(cancellationDisposable, subscription);
}
公共静态IDisposable SchedulePeriod(
这是一个调度程序,
时间间隔,
行动(工作){
if(调度程序==null){
抛出新的ArgumentNullException(“调度程序”);
}
如果(工时==null){
抛出新的异常(“工作”);
}
var cancellationDisposable=新的cancellationDisposable();
var subscription=scheduler.SchedulePeriodic(
间隔
() => {
试一试{
工作(取消一次性.Token);
}捕捉(操作取消异常e){
if(例如CancellationToken!=CancellationDispossible.Token){
//我们传入的令牌以外的其他东西引发了此异常
投掷;
}
}
});
返回新的CompositeDisposable(取消一次性、订阅);
}