Reactive Extensions OnNext thread-safety

前端 未结 3 975
日久生厌
日久生厌 2021-01-01 19:08

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

So the sequence can be generated from multiple sources.

3条回答
  •  独厮守ぢ
    2021-01-01 19:58

    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();
    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(...);
    var syncedObserver = Observer.Synchronize(observer);
    

    Test:

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

提交回复
热议问题