我想创建一个定期调用的函数(1 秒),该函数可能需要超过 1 秒。如果函数未完成,则不应创建新线程。如果它完成,它应该等到适当的时间。哪种计时器方法将是 C# 中的最佳解决方案?
2 回答
0
使用 Microsoft 的响应式扩展 (NuGet "Rx-Main"),您可以执行以下操作:
Observable
.Interval(TimeSpan.FromSeconds(1.0))
.Subscribe(n =>
{
/* Do work here */
});
它等待订阅调用之间的间隔。
于 2016-02-18T10:58:28.880 回答
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.
于 2016-02-18T10:55:30.893 回答