title: Thread Safe calls to Winform controls
body: <p>References:
  <a href="http://msdn.microsoft.com/en-us/library/ms171728.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms171728.aspx</a>
  http://stackoverflow.com/questions/5408155/how-to-make-delegate-thread-sta</p>
  
  <p>I wanted to create a new Thread and make it STA therefore I was not able to use asynchronous delegates or BackgroudWorker (as mentioned in references link 1) Therefore I end up creating a Thread of my own make it STA and attach a callback to know when the Task is complete. The code is something like below and even though I am using invoke required, I still get InvalidOperationException (once in a while)</p>
  
  <pre><code>
  delegate UpdateEventHander(Object sender, EventArgs e);
  class MyTask{
     // to generate an event
     public event UpdateEventHandler Finished;
     public void Start(){
          Result = // something that require the thread to be STA.
          Finished(this, EventArgs.Empty);
     }
     public Result GetResult(){
          return Result;
     }
  }
  
  Class Foo : Form{
     // It has many UI Controls obviously
     public void doSomething(){
        MyTask task = new MyTask();
        task.Finished += new UpdateEventHander(CompletionHandler);
        Thread thread = new Thread(new ThreadStart(task.Start));
        thread.setAppartmetnState(AppartmentState.STA);
        thread.start();
     }
     public void CompletionHandler(Object sender, EventArgs e){
        MyTask task = (MyTask) sender;
        if (oneOfMyControls.InvokeRequired){
           delegateToUpdateUIconrols del = new delegateToUpdateUIconrols(updateUIControls);
           del.invoke();
        }else{
           UpdateUIControls();
        }
     }
     public delegate void delegateToUpdateUIconrols();
     public void UpdateUIControls(){
         // It updates UI controls
         // Datagrid view value properties like backgroud color and stuff.
         // change text in the label.
     }
  
  }
  </code></pre>
  
  <p>Question 1: Which thread will UpdateUIControls execute ? - if you say "Main UI Thread" - then in that case how will the system know if its supposed to run in Main UI thead and NOT some OTHER thread? I am not passing any reference (about Main UI thread) when I call invoke() .. so invoke() is technically executed on the same thread.. </p>
  
  <p>Question 2: Once in a while, I get the InvalidOperationException. Exactly this one
  <a href="http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/6b450a21-e588-414a-afae-9adabfd03674/" rel="nofollow">http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/6b450a21-e588-414a-afae-9adabfd03674/</a></p>
  
  <p>If UpdateUIControls is executing in the main UI thread, there should be not prblem, Right? So, I guess answer to my question really depends upon question 1. </p>
  
  <p>I will appreciate if someone share his/her wisdom on this</p>
  
  <p>Karephul</p>