开发者

Thread Safe calls to Winform controls

References: http://msdn.microsoft.com/en-us/library/ms171728.aspx http://stackoverflow.com/questions/5408155/how-to-make-delegate-thread-sta

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)


delegate UpdateEventHander(Object 开发者_如何学JAVAsender, 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.
   }

}

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..

Question 2: Once in a while, I get the InvalidOperationException. Exactly this one http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/6b450a21-e588-414a-afae-9adabfd03674/

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.

I will appreciate if someone share his/her wisdom on this

Karephul


Controls have thread-affinity; you can only safely talk to them from their creating thread.

You are checking InvokeRequired; however, you are mixing up Delegate.Invoke (runs on the current thread) with Control.Invoke (runs on the UI thread); very different meaning. It should be:

oneOfMyControls.Invoke(del [, args]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜