October 26, 2010 by Christoff Truter C# Threading
When interacting with UI via threads (using Windows Forms) you might have
seen the following exception:
Cross-thread operation not valid: Control 'x' accessed from a thread
other than the thread it was created on.
A Simple way to reproduce this exception, is to simply create a Windows Forms
app, drop a button on the form, attach an event handler on the click event
(of the button) and create a thread that attempts to access the button, for example:
private void action()
{
button1.Text = "Clicked";
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(action);
t.Start();
}
private void action()
{
if (button1.InvokeRequired)
{
button1.Invoke(new Action(action));
return;
}
button1.Text = "Clicked";
}
private void action()
{
button1.Content = "Clicked";
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Thread t = new Thread(action);
t.Start();
}
private void action()
{
if (button1.Dispatcher.CheckAccess())
{
button1.Content = "Clicked";
return;
}
button1.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(action));
}
[EditorBrowsable(EditorBrowsableState.Never)]
Senior Principal Engineer November 7, 2017 by Andrew
Awesome explanation, nothing like it - anywhere. Well done!