C# System.Timers.Timer Class elapsed event and timer 一般注意事项

C# System.Timers.Timer Class elapsed event and timer general precautions

两个问题。

一:在 winforms 应用程序中,在它的 elapsed 事件中启用和禁用 system.timers.timer 以便主 UI 线程可以访问变量是好主意还是坏主意以及在该主 UI 线程上创建的方法?因此,例如使用代码:

myElapsedTimerEvent(object sender, ElapsedEventArgs args)
{
   timer.enabled = false; 
   /***Call some functions and manipulate some variables***/
   timer.enabled = true;
}

二:根据大家的经验,winform和c#中的system.timers.timer有哪些注意事项和注意事项?如果计时器使用不当,您是否可以提供任何有关硬件 and/or 软件可能发生的事情的示例?

如有任何使用 system.timers.timer 的建议,我们将不胜感激。

感谢阅读。

从事件处理程序内部设置定时器的 Enabled 属性 是安全的,前提是事件处理程序在 UI 线程中执行。否则就不安全了,因为定时器的System.Timers.Timerclassis not thread-safe. The make the handler execute in the UI thread you must set the SynchronizingObject属性到当前的Form。例如:

public Form1()
{
    InitializeComponent();
    timer = new Timers.Timer(5000);
    timer.Elapsed += Timer_Elapsed;
    timer.SynchronizingObject = this;
    timer.AutoReset = true;
}

如果我没记错的话,当您使用设计器在 Form 中添加 Timer 时,此分配会自动发生。

不过我的建议是使用 System.Windows.Forms.Timer,因为它没有考虑线程安全。您不仅限于一个计时器。您可以拥有任意数量的它们。请记住,它们的处理程序是 UI 线程中的 运行,因此您应该避免在其中放置冗长的代码,否则 UI 的响应能力可能会受到影响。