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:
- 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?
- Which the advantage of calling method directly (else body) instance via invoker? Does it save resource (CPU, RAM) or something?
Thanks!
ifstatement, it will always be fine, asInvokealready checks if you’re on the UI thread.Invokehas to do a a lot of work to run your method, even if you’re already on the right thread. Here’s what it has to do (extracted from the source of Control.cs):None of the steps in the second branch are required during a direct call from the UI thread, as all the preconditions are already guaranteed, so it’s definitely going to be faster, although to be fair, unless you’re updating controls very frequently, you’re very unlikely to notice any difference.