本文介绍了反应性扩展OnNext线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Rx Subject,从多个线程中调用OnNext()是否是线程安全的?

With the Rx Subject, is it thread-safe to call OnNext() from multiple threads?

因此可以从多个来源生成序列.

So the sequence can be generated from multiple sources.

合并会做同样的事情吗?

Will merge do the same thing?

推荐答案

Rx合同要求通知必须是顺序的,并且这对多个操作员来说是逻辑上的必要.也就是说,您可以使用可用的Synchronize方法来获取此行为.

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线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 20:30