Invoke vs BeginInvoke

来源:互联网 发布:app美图软件 编辑:程序博客网 时间:2024/06/06 17:01
  • Control的Invoke和BeginInvoke:
Control.Invoke 方法 (Delegate) :在拥有此控件的基础窗口句柄的线程(UI thread)上执行指定的委托。
Control.BeginInvoke 方法 (Delegate) :在创建控件的基础句柄所在线程(UI thread)上异步执行指定委托。
Control的Invoke和BeginInvoke的参数为delegate,委托的方法是在Control的线程上执行的,也就是我们平时所说的UI线程。
使用场合:在工作线程中去更新界面显示。
做法:将工作线程中涉及更新界面的代码封装为一个方法,通过control的 Invoke 或者 BeginInvoke 去调用,两者的区别就是一个导致工作线程等待(Invoke),而另外一个则不会(BeginInvoke)。

界面的正确更新始终要通过 UI 线程去做,我们要做的事情是在工作线程中包揽大部分的运算,而将对纯粹的界面更新放到 UI 线程中去做
  • Delegate的Invoke和BeginInvoke
If in UI thread, for example in UI class, we can implement as follows,
(1) define function for worker thread
      private delegate int WorkerAsync(int i);
      private int WorkerAsyncImpl(int i) // What to do in worker thread.
{
// Implementation.
// Do something in worker thread.
}

private void WorkerAsyncCompleted(IAsyncResult ar) // What to do after worker thread completes.
{
 xxx _extraparam = (xxx)(ar.AsyncState); //_extraparam should be the extraparam input in OnMouseClick.
AsyncResult result = ar as AsyncResult;
WorkerAsync wa = (result.AsyncDelegate) as WorkerAsync;
int res = wa.EndInvoke(ar); // res is the return value of WorkerAsyncImpl();

this.Dispatcher.Invoke(new Action(delegate
{
// Update UI using res;
}), null);
}
(2) In UI function, for example
void onMouseClick()
{
int i = get from UI;
WorkerAsync wa = new WorkerAsync(WorkerAsyncImpl);
IAsyncResult ar = wa.BeginInvoke(i, WorkerAsyncCompleted, extraparam);
// Usually we can use extraparam as a tag to differentiate different async worker thread inWorkerAsyncCompleted() ;
}

原创粉丝点击