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

时间:2009-04-07 13:35:24

标签: c# winforms timer

原帖:How to access a timer from another class in C#

我尝试了一切。

- 活动

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

- 公共/内部财产

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

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

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

4 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:6)

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

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

答案 2 :(得分:1)

我意外地试图再次使用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;
    }

答案 3 :(得分:1)

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

public static class ControlExtensions
{
  public static TResult InvokeEx<TControl, TResult>(this TControl control,
                            Func<TControl, TResult> 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秒后立即恢复生机。