reactive extension OnNext

前提是你 提交于 2019-12-05 14:11:31

问题


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

So the sequence can be generated from multiple source.

With merge do the same thing?


回答1:


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);            

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);

Test:

        Func<int, Action> onNext = i => () => syncedSubject.OnNext(i);
        Parallel.Invoke
        (
            onNext(1),
            onNext(2),
            onNext(3),
            onNext(4)
        );



回答2:


No, sequences are meant to be sequential, hence no overlapping notifications are allowed. You can use Synchronize extension methods to enforce proper synchronization. Operators like Merge take a lock to call the downstream observer in order to ensure proper serial invocation on On* callbacks.




回答3:


Calling someSubject.OnNext() is as thread-safe as someList.Add() - you can call it from > 1 thread, but not concurrently. Wrap your OnNext in a lock statement and it'll be safe.



来源:https://stackoverflow.com/questions/12270642/reactive-extension-onnext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!