My Timer event crashes because the events are call

2019-02-27 13:50发布

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:

using System;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Timers;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        System.Timers.Timer T = new System.Timers.Timer();
        public Form1()
        {
            InitializeComponent();
            T.Elapsed += new ElapsedEventHandler(T_Elapsed);
            T.Start();
        }

        void T_Elapsed(object sender, ElapsedEventArgs e)
        {
            label1.Text = "This will not work";
        }
    }
}

I thought events ran in the same thread as they were triggered in.

8条回答
孤傲高冷的网名
2楼-- · 2019-02-27 14:43

Are you remembering to use InvokeRequired? It will allow you to update a UI element on the UI thread from the Timer thread.

查看更多
We Are One
3楼-- · 2019-02-27 14:45

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";
  }
}
查看更多
登录 后发表回答