Send a backgroundworker to sleep while checking for cancellation

后端 未结 3 841
悲&欢浪女
悲&欢浪女 2021-01-06 01:34

I have a background worker which updates the GUI on a regular basis via ReportProgress.

The update occurs at regular intervals, every 5 seconds for example, or it c

3条回答
  •  一向
    一向 (楼主)
    2021-01-06 01:45

    Or even better, use the Reactive Extensions framework and have a "worker" observe a stream of interval events. The stream can then easily be disposed to stop generating new events, thus terminating the worker. Combine this with a cancellation disposable and you have one single disposable to stop both the interval timer and any worker doing its work:

    var cancel = new BooleanDisposable();
    var subscription = Observable.Interval(TimeSpan.FromSeconds(20))
                                 .ObserveOn(Scheduler.DispatcherScheduler)
                                 .Subscribe(i => PerformWorkOnUI(cancel));
    var uiWork = new CompositeDisposable(cancel, subscription);
    

    To cancel the stream of timer events, you only have to dispose the composite cancellation/subscription:

    uiWork.Dispose();
    

    Clarification: ObserveOn(Scheduler.DispatcherScheduler) ensures that the subscription will be called on the dispatcher thread.

提交回复
热议问题