2

我是 RX 的新手,并且正在玩一些示例,关于为什么未调用订阅中的 Console.writeLine 的任何想法?

var obs = Observable.Create(i => {

              while(true)
            {
                Thread.Sleep(250);

                i.OnNext(2.0);
            }



            return () => { };
        })        
        .SubscribeOn(Scheduler.TaskPool)   
        .ObserveOn(Scheduler.CurrentThread)
        .Subscribe(i =>
        {
            Console.WriteLine("Inside Subscribe");
        });

如果我删除

.ObserveOn(Scheduler.CurrentThread) 

行一切都好吗?

谢谢

4

1 回答 1

4

正如我所提到的SubscribeOnObserveOn并不是最好的方法;我强烈建议您通读此书:

http://blogs.msdn.com/b/rxteam/archive/2009/11/21/observable-context-observable-subscribeon-and-observable-observeon.aspx

基本上,SubscribeOn告诉系统在什么上下文上进行实际的订阅/取消订阅连接,同时ObserveOn告诉系统当新值到达源时“执行为”什么上下文。

首先,请允许我稍微调整一下您的示例:

Console.WriteLine("Start Thread ID:{0}", Thread.CurrentThread.ManagedThreadId);
var subscription = Observable.Create<double>(i => 
    {
        Console.WriteLine("Observable thread ID:{0}", Thread.CurrentThread.ManagedThreadId);
        while(true)
        {
            Console.WriteLine("Pushing values from thread {0}", Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(250);            
            i.OnNext(2.0);
        }
        return () => { };
    })        
    .SubscribeOn(Scheduler.TaskPool)   
    .ObserveOn(Scheduler.CurrentThread)
    .Subscribe(i =>
    {
        Console.WriteLine("Subscribable thread ID:{0}", Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine("Inside Subscribe");
    });    
Console.ReadLine();
subscription.Dispose();

如果你运行它,你会看到类似的东西:

Start Thread ID:21
Observable thread ID:23
Pushing values from thread 23
Pushing values from thread 23
Pushing values from thread 23
Pushing values from thread 23

ObserveOn现在让我们交换我们和的线程SubscribeOn

.SubscribeOn(Scheduler.CurrentThread)   
.ObserveOn(Scheduler.TaskPool)

现在我们得到:

Start Thread ID:26
Observable thread ID:26
Pushing values from thread 26
Pushing values from thread 26
Subscribable thread ID:27
Inside Subscribe
Pushing values from thread 26
Subscribable thread ID:27
Inside Subscribe
Pushing values from thread 26
Subscribable thread ID:27
Inside Subscribe
于 2013-05-06T15:34:37.943 回答