为什么在Observable.Dispose()上永远不会取消此CancellationDisposable? [英] Why this CancellationDisposable never get canceled on Observable.Dispose()?

查看:508
本文介绍了为什么在Observable.Dispose()上永远不会取消此CancellationDisposable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WinForms应用程序中使用RxFramework。我试图运行一个Observable异步并使用CancellationDisposable取消用户单击按钮时的操作。但它不起作用!
Im using RxFramework within an WinForms app. Im trying to run an Observable async and using the CancellationDisposable to cancel the operation when user clicks a button. but it is not working!

推荐答案

一次性丢弃后才能丢弃,但是在
返回之前您的可观察支票取消取消; 已执行。

The disposable can't be disposed until it's returned, but your observable checks for cancellation before return cancel; is executed.

请尝试在源头安排工作,而不是使用 SubscribeOn 。 这是在
中根据§ 6.9创建新的observable的推荐方法 Rx设计指南

Instead of using SubscribeOn, try scheduling the work at the source.  This is the recommended way to create a new observable according to §6.9 in the Rx Design Guidelines.

如果您只需要一个标志而不是真正的取消令牌,则可以使用 BooleanDisposable ,但行为是相同的。

You can use BooleanDisposable if you only need a flag instead of a real cancellation token, although the behavior is the same.

请注意,Rx提供了一个生成运算符,可以代替
创建来简化您的特定可观察量。

Note that Rx provides a Generate operator that can be used instead of Create to simplify your particular observable.

例如:


var countObserver = Observable.Create<int>(
	observer =>
	{
		var cancel = new BooleanDisposable();

		var schedule = Scheduler.ThreadPool.Schedule(() =>
			{
				for (int i = 0; i < 100 && !cancel.IsDisposed; i++)
				{
					observer.OnNext(i);

					Thread.Sleep(1000);
				}

				observer.OnCompleted();
			});

		return new CompositeDisposable(cancel, schedule);
	});


这篇关于为什么在Observable.Dispose()上永远不会取消此CancellationDisposable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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