Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

A question about form controls invoke function.
Control1 is created on thread1. If you want to update something in Control1 from thread2 you must do something like:

delegate void SetTextCallback(string txt);  

void setText(string txt)  
{  
  if (this.textBox1.InvokeRequired)  
  {  
     SetTextCallback d = new SetTextCallback(setText);  
     this.Invoke(d, new object[] { txt });  
  }  
  else  
  {   
     // this will run on thread1 even when called from thread2
     this.textBox1.AppendText(msg);  
  }  
}`  

What happens behind the scenes here?

This invoke behaves different from a normal object invoke. When you want to call a function in an object on a specific thread, then that thread must be waiting on some queue of delegates, and execute the incoming delegates.

Is it correct that the windows forms control invoke function is completely different from the standard object invoke function?

share|improve this question
add comment

1 Answer

To prevent thread issues, many Windows Forms operations have to happen on the UI thread. Invoke provides an easy way of accomplishing this without explicit thread management.

If you are curious about the internal workings, I would download a decompile tool (I believe Telerik JustDecompile is free) and look at System.Windows.Forms.Control.Invoke in the System.Windows.Forms DLL in the GAC.

BTW, it looks like it loads a reference to the UI thread and invokes your code in its environment.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.