如何同步System.Reactive中可观察到的结果

问题描述 投票:1回答:1

因此,Rx默认情况下是单线程的。对于Sample运算符,则不是。在我的ASPNetCore应用程序中,我希望能够在主线程(单线程)上运行Subscribe。我尝试使用ObserveOn传入SynchronizationContext.Current,但它是ASPNetCore中的null

[一种可能的解决方案是将所有项目都放入BlockingCollection,然后从中读取,但这有点增加了另一层复杂性。

      Console.WriteLine ($"Main Thread:  {Thread.CurrentThread.ManagedThreadId}");
      var source = Observable
        .Interval (TimeSpan.FromSeconds (1))
        .Sample (TimeSpan.FromSeconds (2));

      source
        .Subscribe (
          data => {
            Console.WriteLine ($"{Thread.CurrentThread.ManagedThreadId}"); // different thread
            // Here each onNext is invoked asynchronously 
            // But I have a shared resource that I would like to invoke synchronously. 
          }
        );

任何建议将不胜感激:)。

因此,Rx默认情况下是单线程的。对于Sample运算符,则不是。在我的ASPNetCore应用程序中,我希望能够在主线程(单线程)上运行订阅。我尝试过...

asp.net-core asynchronous system.reactive blockingcollection
1个回答
0
投票

如果要在主线程上进行调度,则应为操作员指定调度程序。

© www.soinside.com 2019 - 2024. All rights reserved.