Tuesday, May 22, 2012

Why do we need the directly call in a thread-safe call block?

Refer the thread-safe call tutorial at MSDN, have a look at following statments:



// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired) {
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
} else {
this.textBox1.Text = text;
}


Of course, I've used it many times in my codes, and understand a little why to use it.
But I still have some unclear questions about those statements, so anybody help me to find them out, please.



The questions are:




  1. Will the code can run correctly with the statements in the if body only? I tried and seems it just cause the problem if the control is not initialize completely. I don't know is there more problem?

  2. Which the advantage of calling method directly (else body) instance via invoker? Does it save resource (CPU, RAM) or something?



Thanks!





No comments:

Post a Comment