在特定时间后执行动作,但如果是手动调用,则重置计时器

Yog*_*esh 4 c# timer system.reactive reactive

我正在使用System.Timers.Timer每 10 秒执行一次操作。如果出现某些特殊情况或通过 UI,也可以通过其他方法调用此操作。如果没有从计时器调用该操作,我只需重置计时器。

我正在使用的代码...

timer = new Timer();
timer.Elapsed += (sender, args) => ExecuteAction();
timer.Interval = 10000;
timer.Enabled = true;

public void ExecuteActionAndResetTimer()
{
    ExecuteAction();

    timer.Stop();
    timer.Start();
}

private void ExecuteAction()
{
    // do the work...
}
Run Code Online (Sandbox Code Playgroud)

预期的结果,如果“X”是从计时器(即,所谓的动作ExecuteAction),“ X ”从外部计时器(即所谓的动作ExecuteActionAndResetTimer)和“o”是第二:

XooooXo X o X ooooXo X ooooX

这工作正常。我只想知道我们可以使用反应式扩展来做到这一点吗?

谢谢。

Eni*_*ity 5

是的,这很容易用 Rx 完成。

就是这样:

var subject = new Subject<char>();

var query =
    subject
        .StartWith('X')
        .Select(c =>
            Observable
                .Interval(TimeSpan.FromSeconds(10.0))
                .Select(n => 'X')
                .StartWith(c))
        .Switch();

query.Subscribe(x => Console.Write(x));

Thread.Sleep(5000);
subject.OnNext('Q');
Thread.Sleep(15000);
subject.OnNext('W');
Run Code Online (Sandbox Code Playgroud)

这产生了XQXWXXXX最后一个Xs 无限循环的序列。