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.
Are you remembering to use InvokeRequired? It will allow you to update a UI element on the UI thread from the Timer thread.
Yes, events are executed in the same thread which triggered them. It just so happens that
System.Timers.Timer
uses aThreadPool
thread by default when raising theElapsed
event. Use theSynchronizingObject
property to cause theElapsed
event handler to execute on the thread hosting the target object instead.