如何使用Rx以非阻塞方式观察值? [英] How can I observe values in a non blocking way using Rx?
问题描述
我正在尝试观察一个计时器,该计时器的处理程序长于该间隔.为了做到这一点,我想将观察时间安排在某种threadPool,任务池之类的东西上.
I'm trying to observe on a timer which its handler is longer then the interval. in order to do so I want to schedule the observation on some kind of threadPool, task pool or something.
我尝试了线程池,任务池和newthread,但是它们都不起作用.有谁知道该怎么做?例如:
I tried threadpool, taskpool, and newthread and none of them worked. Does anyone knows how to do it ? example:
var disposable = Observable.Timer(TimeSpan.Zero, TimeSpan.FromMilliseconds(100)).ObserveOn(Scheduler.NewThread).
Subscribe(x =>
{
count++;
Thread.Sleep(TimeSpan.FromMilliseconds(1000));
});
Thread.Sleep(TimeSpan.FromSeconds(5));
disposable.Dispose();
if (count > 10 )
{
//hurray...
}
推荐答案
您要问的是一个不好的主意,因为您最终将耗尽可用资源(因为创建线程的速度>线程完成的速度).相反,为什么在上一个项目完成后不安排新项目呢?
What you're asking is a bad idea to do, because you'll eventually exhaust available resources (since the rate of creating threads > the thread finishing rate). Instead, why don't you schedule a new item when the previous one is finished?
在您的特定示例中,您需要将IScheduler传递给Observable.Timer,而不是尝试使用ObserveOn.
In your specific example, you need to pass an IScheduler to Observable.Timer instead of trying to use ObserveOn.
这篇关于如何使用Rx以非阻塞方式观察值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!