I’m changing the Text of a button from a BackgroundWorker and it works. I thought that was supposed to throw an exception. Why doesn’t it?
Why don’t I get a Cross-thread operation not valid: ... accessed from a thread other than the thread it was created on.?
EDIT: Thanks everyone.
Perhaps the reason was that there was a: Thread.Sleep(1000); on the UI.
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerAsync();
Thread.Sleep(1000);
}
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
button1.Text = "a";
}
However, I noticed that this following code runs fine as well, despite affecting the UI (indirectly).
public partial class Form1 : Form
{
int i;
public Form1()
{
InitializeComponent();
i = 1;
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerAsync();
for (int j = 0; j < 100000000; j++) ;
button1.Text = i.ToString();
}
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
i = 2;
}
}
Why?
The answer is probably that cross thread operations can be executed. They’re just prone to trouble. And a
Control(which is supposed to throw an exception) probably doesn’t ‘mind’ cross threading when it’s aSleep.