Reputation: 937
It seems that C# throws exceptions for cross-threading operations sometimes. For example, you can try running this sample code in a Windows Forms program:
public Form1()
{
InitializeComponent();
Thread setTextT = new Thread(TextSetter);
setTextT.Start();
}
private void TextSetter()
{
//Thread.Sleep(4000);
textBox1.Text = "Hello World";
}
It doesn't throw any exceptions, everything seems to be working fine. Now, when you uncomment the Thread.Sleep line, it'll throw an exception for attempted cross-threading access.
Why is this the case?
Upvotes: 2
Views: 125
Reputation: 4919
Try this:
public Form1()
{
InitializeComponent();
Thread setTextT = new Thread(TextSetter);
setTextT.Start();
}
private void TextSetter()
{
//Thread.Sleep(4000);
//textBox1.Text = "Hello World";
//You have to Invoke your action to the UI thread
Invoke(new Action(()=>textBox1.Text = "Hello World"));
}
Upvotes: 0
Reputation: 127563
It is because the cross thread check only happens after the window's handle has been created, as the thing you are checking for is cross thread accessing of the window handle. When you don't have the sleep in there the code runs quickly enough before the control is displayed for the the first time (the handle gets created the first time the control is displayed).
The easyist way to know if you need to be careful of cross thread access of a UI control is just check InvokeRequired
and if it is true you need to call Invoke
(or BeginInvoke
if you don't want to wait for it to complete) to get on the thread that created the control.
Upvotes: 5