在C#中同步定时器回调

时间:2016-02-18 10:52:44

标签: c# timer periodic-processing

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

2 个答案:

答案 0 :(得分:0)

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.

答案 1 :(得分:0)

使用Microsoft的Reactive Extensions(NuGet“Rx-Main”),您可以这样做:

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

等待订阅电话之间的间隔。