System.reactive计时器 - 如何动态更改间隔?
问题描述:
我正在使用System.Reactive开发以下(简化版)类。现在,它每1秒滴答一次,但为了减少CPU的工作量,我想计算我感兴趣的下一个日期时间,并相应地设置一个新的间隔。该新间隔可以与当前设置的间隔不同或不同。这是带注释的类:
I am developing the following (simplified version of) class with System.Reactive. Right now, it ticks every 1 second, but in an effort to reduce workload on the CPU, I want to calculate the next datetime I'm interested in, and set a new interval accordingly. This new interval may or may not be different from the currently set interval. Here's the annotated class:
public class Class1
{
public IObservable<long> Timer;
public IDisposable TimerSub;
DateTime NextTime = new DateTime(0);
public Class1()
{
this.NextTime = new DateTime(0);
this.Timer = Observable.Timer(TimeSpan.FromSeconds(1));
this.TimerSub = this.Timer.Subscribe(x => DoWork());
}
private void DoWork()
{
bool canWork = (this.NextTime.Ticks != 0);
this.NextTime = this.CalculateFutureDate();
// change the timer interval to "this.NextTime - DateTime.Now"
// how do I do this?
if (canWork)
{
// Do some work stuff...
}
}
private DateTime CalculateFutureDate()
{
return DateTime.Now.AddDays(1);
}
}
我的尝试:
谷歌搜索,但没有任何结果是有道理的。
What I have tried:
googling, but nothing came up that made any sense.
答
我最终重新重新创建 IObservable
并按照上面的建议重新订阅。我不喜欢这样做,但这是处理问题最方便的方法。
I ended up re-recreating the IObservable
and re-subscribing as suggested above. I didn't like doing it that way, but it's the most expedient way to handle the problem.