My Timer event crashes because the events are called on a different thread

前端 未结 8 1778
再見小時候
再見小時候 2021-01-21 10:49

I get the error \"Cross-thread operation not valid: Control \'label1\' accessed from a thread other than the thread it was created on.\" when I run this code:

us         


        
8条回答
  •  孤独总比滥情好
    2021-01-21 11:25

    Yes, events are executed in the same thread which triggered them. It just so happens that System.Timers.Timer uses a ThreadPool thread by default when raising the Elapsed event. Use the SynchronizingObject property to cause the Elapsed event handler to execute on the thread hosting the target object instead.

    public partial class Form1 : Form
    {
      System.Timers.Timer T = new System.Timers.Timer();
    
      public Form1()
      {
        InitializeComponent();
        T.Elapsed += new ElapsedEventHandler(T_Elapsed);
        T.SynchronizingObject = this;
        T.Start();
      }
    
      void T_Elapsed(object sender, ElapsedEventArgs e)
      {
        label1.Text = "This will not work";
      }
    }
    

提交回复
热议问题