gpt4 book ai didi

c# - RX ObserveOn 问题

转载 作者:行者123 更新时间:2023-11-30 20:58:02 27 4
gpt4 key购买 nike

我是 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) 

线路一切正常吗?

谢谢

最佳答案

正如我提到的,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

现在让我们交换 ObserveOnSubscribeOn 的线程:

.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

关于c# - RX ObserveOn 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16382312/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com