C# 中的同步计时器回调

本文关键字:计时器 回调 同步 | 更新日期: 2023-09-27 18:35:15

我想创建一个定期调用的函数(1 秒),该函数可能需要 1 秒以上。如果函数未完成,则不应创建新线程。如果它完成,它应该等到到期时间。哪种计时器方法是 C# 中的最佳解决方案?

C# 中的同步计时器回调

使用 Microsoft 的反应式扩展 (NuGet "Rx-Main") 可以执行以下操作:

Observable
    .Interval(TimeSpan.FromSeconds(1.0))
    .Subscribe(n =>
    {
        /* Do work here */
    });

它等待订阅调用之间的间隔。

Timer timer = new Timer();//Create new instance of "Timer" class.
timer.Interval = 1000;//Set the interval to 1000 milliseconds (1 second).
bool started = false;//Set the default value of "started" to false;
timer.Tick += (sender, e) =>//Set the procedure that occurs each second.
{
    if (!started)//If the value of "started" is false (if it isn't running in another thread).
    {
        started = true;//Set "started" to true to ensure that this code isn't run in another thread.
        //Other code to be run.
        started = false;//Set "started" to false so that the code can be run in the next thread.
    }
};
timer.Enabled = true;//Start the timer.