2012-02-07 176 views
0

我有下面的代碼(但不工作)。我需要等待,直到線程完成其工作,然後再執行下一個命令我該如何等待線程完成其作業,然後執行下一個命令c#?

private void btnPaste_Click(object sender, EventArgs e) 
    { 
     if (copiedItems != null) 
     { 
      if (copy) 
      { 
       System.Threading.Thread thPASTE = new System.Threading.Thread(PasteFromCopy); 
       thPASTE.Start(currAddress); 
       lock (this) 
       { 
        btnRefresh_Click(sender, e); 
       } 
      } 
      else 
      { 
       System.Threading.Thread thPASTE = new System.Threading.Thread(PasteFromMove); 
       thPASTE.Start(currAddress); 
       lock (this) 
       { 
        btnRefresh_Click(sender, e); 
       } 
      } 
     } 
    } 

粘貼應該做一些代碼,然後後,我應該刷新列表即時消息顯示..我需要這樣做,因爲它不適用於我當我調用線程刷新
我該怎麼做?

+0

您可能還需要考慮一個私人鎖定變量,而不是採取鎖'this'。例如'私人只讀對象lockObject =新對象();'你可以看到這個線程的更多細節http://stackoverflow.com/questions/251391/why-is-lockthis-bad – 2012-02-07 22:36:33

+0

有沒有必要開始一個線程和然後等待它。你也可以直接調用PasteFromCopy() – 2012-02-08 01:31:16

回答

5

您可以在線程實例上使用Join方法,該方法將阻塞調用線程,直到其他線程完成。

1

i need to do it this way, because it doesn't work for me when i call the refresh in the thread

因爲輔助線程是不是你的問題是不是與線程同步像JoinWaitWaitOne

從Windows窗體輔助線程更新用戶界面元素是棘手的相關允許直接從表單或其任何子控件讀取或寫入屬性值。存在此限制是因爲Windows窗體中的表單對象和控件對象不是線程安全的。這是允許的直接訪問窗體或其控件之一的屬性值的唯一線索是主UI線程

要更新從一個線程的GUI(等你的主線程),你需要調用InvokeBeginInvoke表單(或某些控件)的方法將委託插入到UI線程的分派器中。

這些鏈接可以幫助你。

How to update GUI from another thread in C#?

Updating the UI from a Secondary Thread

Updating the GUI from another thread made easy

相關問題