2015-02-24 57 views
0

我想從工作線程中的控件讀取值。調用的潛在同步問題?

public void worker() 
    { 
     while (true) 
     { 
      ewh.WaitOne(); 

      int index = -1; 
      this.Invoke((MethodInvoker)delegate() 
      { 
       index = this.comboBoxSource.SelectedIndex; 
      }); 

      // using index here 

據我所知,Invoke是異步啓動的。我是對的,在我使用index的地方沒有保證,Invoke會完成它的工作嗎?如果是這樣,我怎樣才能使調用作爲阻止操作?

+1

'Invoke' **是**阻塞。'BeginInvoke'('InvokeAsync')是異步版本。 – Sinatr 2015-02-24 10:58:52

回答

3

據我所知,Invoke是異步啓動的。

不,Invoke是同步的,因爲它會阻塞,直到委託在UI線程中完成。不幸的是,這在Control.Invoke(Delegate)中沒有明確記錄。另過載(Control.Invoke(Delegate, object[])指出,它是ISynchronizeInvoke.Invoke執行當中更清晰:

不像BeginInvoke,此方法將同步運行,也就是說,它會等待直到進程返回之前完成呼叫時拋出的異常傳播回給調用者