如何从不同的线程/类启用计时器

原帖: 如何从C#中的另一个类访问一个计时器

我尝试了一切。

-事件

-Invoke无法完成,因为Timers没有InvokeRequired属性。

– 公共/内部财产

没有任何工作,代码正在执行,timer.Enabled属性被设置为“true”,但它没有Tick.If我调用事件或只是在非静态方法中从表单类更改属性 – 它确实打勾和工作。

我从来不知道这会花费我一天时间,甚至可能更多地获得如何使用体面的计时器。

如果没有办法做到这一点,还有什么我可以使用的与计时器类似的工作(延迟,启用/禁用)?

如果需要multithreading支持,则应该使用System.Timers命名空间中的Timer类,而不是WinForms Timer控件。 有关更多信息,请查看WinForms Timer控件的MSDN文档:

http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

您不需要在Control iteself上检查InvokeRequired,您可以检查类上的属性,例如:

 if (this.InvokeRequired) { BeginInvoke(new MyDelegate(delegate() { timer.Enabled = true; })); } 

我意外地试图再次使用invoke,这次它有效,但我会接受你的回答,DavidM。

  public bool TimerEnable { set { this.Invoke((MethodInvoker)delegate { this.timer.Enabled = value; }); } } public static void timerEnable() { var form = Form.ActiveForm as Form1; if (form != null) form.TimerEnable = true; } 

仅仅因为System.Windows.Forms.Timer没有调用的能力,并不意味着你的表单没有。 从第二个(或其他)线程尝试我的InvokeEx以启用计时器。

 public static class ControlExtensions { public static TResult InvokeEx(this TControl control, Func func) where TControl : Control { if (control.InvokeRequired) { return (TResult)control.Invoke(func, control); } else { return func(control); } } } 

有了这个,以下代码对我有用:

 new Thread(() => { Thread.Sleep(1000); this.InvokeEx(f => f.timer1.Enabled = true); }).Start(); 

并且计时器在1秒后立即恢复生机。