How to allow canceled work using the IScheduler.SchedulePeriodic Rx method in .NET 4

I want to run some work periodically using the IScheduler.SchedulePeriodic method in Rx. I want to be able to cancel the work not only between execution, but also (jointly) while working, allowing the work to accept CancellationToken, which is canceled when the IDisposable returns from SchedulePeriodic.

The disposal of IDisposable should not be blocked until the work is canceled, just provide the opportunity for the work to cancel itself at the next opportunity.

How to do this with Rx in .NET 4.0?

Looks like support for collaborative undo support has been added in Rx 2 (see "Making schedulers easier to use with" wait ") help with this, but it's not available in .NET 4.

+4
source share
1 answer

This is the extension method I came across:

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);
}
+4
source

All Articles