多線程更新主界面上的DataGrid
這是一個(gè)多線程更新DataGrid的例子。場(chǎng)景如下:目標(biāo)是將DataGrid中的數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫(kù),由于DataGrid中的數(shù)據(jù)不是完全正確的,所以對(duì)于錯(cuò)誤的數(shù)據(jù)要保留下來(lái),讓用戶去改,改了之后再導(dǎo),導(dǎo)了再改,改了再導(dǎo)直到全部導(dǎo)進(jìn)數(shù)據(jù)庫(kù)為止。
基本的思路是:主GUI上有一個(gè)DataGrid,然后新開(kāi)一個(gè)線程進(jìn)行導(dǎo)入。線程導(dǎo)入數(shù)據(jù)后,把收集到的錯(cuò)誤數(shù)據(jù)一次性返給主線程,然后顯示在原來(lái)這個(gè)DataGrid中,提供給用戶更改并再次導(dǎo)入。
發(fā)起一個(gè)線程很容易,這里就不講了,直接進(jìn)入主題,如果更新主界面上的DataGrid。由于在 .Net中由線程A創(chuàng)建的 控件是不允許其他線程直接修改的。因此,其他線程需要委托線程A,把需要更新的數(shù)據(jù)給線程A,由他自己去更新。
看如何實(shí)現(xiàn)的:
??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執(zhí)行完成!";
???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;
}
關(guān)鍵在于在主線程聲明一個(gè)委托:private delegate void ReBindDataGrid_Delegate(DataTable dt);然后在導(dǎo)入線程的完成事件中,利用這個(gè)委托,執(zhí)行主線程中的方法:ReBindDataGrid,同時(shí)把參數(shù)傳給他。
OK,這樣就完成了。
關(guān)于兼講委托,只一句話,委托就是在二個(gè)不能直接相互操作的對(duì)象之間,建立一個(gè)橋梁。例如二個(gè)線程之間。
from: http://www.wintle.cn/article.asp?id=127
posted on 2006-12-27 11:20 weidagang2046 閱讀(1338) 評(píng)論(0) 編輯 收藏 所屬分類: Windows