這是一個多線程更新DataGrid的例子。場景如下:目標是將DataGrid中的數據導入到數據庫,由于DataGrid中的數據不是完全正確的,所以對于錯誤的數據要保留下來,讓用戶去改,改了之后再導,導了再改,改了再導直到全部導進數據庫為止。
基本的思路是:主GUI上有一個DataGrid,然后新開一個線程進行導入。線程導入數據后,把收集到的錯誤數據一次性返給主線程,然后顯示在原來這個DataGrid中,提供給用戶更改并再次導入。
發起一個線程很容易,這里就不講了,直接進入主題,如果更新主界面上的DataGrid。由于在 .Net中由線程A創建的 控件是不允許其他線程直接修改的。因此,其他線程需要委托線程A,把需要更新的數據給線程A,由他自己去更新。
看如何實現的:
??private delegate void ReBindDataGrid_Delegate(DataTable dt);
??private void ReBindDataGrid(DataTable dt)
??{
???this.dgList.DataSource = dt.DefaultView;
???this.dgList.Refresh();
??}
??private void import_ThreadCompleted(object sender, ThreadCompletedArgs e)
??{
???this.lblIntro.Text += "\n執行完成!";
???if(e.ErrorRows != null)
???{
????ReBindDataGrid_Delegate dt = new ReBindDataGrid_Delegate(ReBindDataGrid);
????this.Invoke(dt,new object[]{e.ErrorRows.Copy()});
???}
???else
???{
????this.pBar.Value = 0;
????this.rtxtInfo.Text += "..Over!";
??}
???this.dgList.Enabled = true;
}
關鍵在于在主線程聲明一個委托:private delegate void ReBindDataGrid_Delegate(DataTable dt);然后在導入線程的完成事件中,利用這個委托,執行主線程中的方法:ReBindDataGrid,同時把參數傳給他。
OK,這樣就完成了。
關于兼講委托,只一句話,委托就是在二個不能直接相互操作的對象之間,建立一個橋梁。例如二個線程之間。
from: http://www.wintle.cn/article.asp?id=127