How to enable a timer from a different thread/class

前端 未结 4 882
心在旅途
心在旅途 2020-12-21 05:27

Original post: How to access a timer from another class in C#

I tried everything.

-Event

-Invoke can\'t be done,because Timers don\'

相关标签:
4条回答
  • 2020-12-21 06:03

    You should use the Timer class from the System.Timers namespace, and not the WinForms Timer control, if you want multi-threading support. Check the MSDN documentation for the WinForms Timer control for more information:

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

    0 讨论(0)
  • 2020-12-21 06:17

    Just because System.Windows.Forms.Timer doesn't have the ability to invoke, doesn't mean that your form doesn't. Try my InvokeEx from the second (or other) thread to enable the timer.

    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);
        }
      }
    }
    

    With this, the following code worked for me:

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

    And the timer instantly sprung to life after the 1 second.

    0 讨论(0)
  • 2020-12-21 06:21

    You don't need to check InvokeRequired on the Control iteself, you can check the property on the class e.g.:

    if (this.InvokeRequired) 
    { 
        BeginInvoke(new MyDelegate(delegate()
        {
            timer.Enabled = true;
        }));
    }
    
    0 讨论(0)
  • 2020-12-21 06:26

    I accidently tried to use invoke again,this time it worked,but I'll accept your answer,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;
        }
    
    0 讨论(0)
提交回复
热议问题