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