本文介绍了反应扩展OnNext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有了RX Subject,从多线程调用 OnNext()
是否是线程安全的?
With RX Subject, is it thread-safe to call OnNext()
from multiple threads?
与合并做同样的事情?
推荐答案
Rx合同要求通知是顺序的,并且对于几个运算符是逻辑必要的。也就是说,您可以使用可用的同步
方法来获取此行为。
The Rx contract requires that notifications be sequential, and is a logical necessity for several operators. That said, you can use the available Synchronize
methods to get this behaviour.
var subject = new Subject<int>();
var syncedSubject = Subject.Synchronize(subject);
现在可以并发调用 syncedSubject
中。
对于必须同步的观察者,您还可以使用:
You can now make concurrent calls to syncedSubject
.For an observer which must be synchronized, you can also use:
var observer = Observer.Create<Unit>(...);
var syncedObserver = Observer.Synchronize(observer);
测试:
Func<int, Action> onNext = i => () => syncedSubject.OnNext(i);
Parallel.Invoke
(
onNext(1),
onNext(2),
onNext(3),
onNext(4)
);
这篇关于反应扩展OnNext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!