So why is it that we need to use the Invoke method when updating the GUI?
The following is the way we are suppose to update GUI components:
-
delegate void textIt(object o);
-
public partial class Form1 : Form
-
{
-
public Form1()
-
{
-
InitializeComponent();
-
}
-
private void Form1_Load(object sender, EventArgs e)
-
{
-
//Main Thread
-
Label l = new System.Windows.Forms.Label();
-
this.Controls.Add(l);
-
-
System.Threading.Thread testThread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(testStart));
-
testThread.Start(l);
-
-
}
-
private void testStart(object o)
-
{
-
//testThread
-
if (((Label)o).InvokeRequired)
-
{
-
textIt t = new textIt(testStart);
-
this.Invoke(t, o);
-
}
-
else
-
{
-
((Label)o).Text = "TEST";
-
}
-
}
-
}
-
If I delete the delegate and change the method testStart(object o) to:
-
private void testStart(object o)
-
{
-
((Label)o).Text = "TEST";
-
}
-
I don't get any problems. In fact, I have yet to have a problem with X number of threads changing the GUI directly as long as I implement mutual exclusion correctly.
I have read that the properties
cannot be changed by any thread other then the one that created it. Is that a suggestion or a fact? If it is a suggestion, then what could go wrong? If it is a fact then how is it that I have been accessing the properties directly from different threads? does the compiler rewrite the code so that it does call Invoke?