在C# 的應用程序開發中, 我們經常要把UI線程和工作線程分開,防止界面停止響應, 同時我們又需要在工作線程中更新UI界面上的控件。但直接訪問會出現“線程間操作無效”的情況,因為.NET禁止了跨線程調用控件, 否則誰都可以操作控件,最后可能造成錯誤。 下面介紹幾種跨線程訪問的方法:
1、禁止對跨線程訪問做檢查 (不推薦使用這種方法)
這種方法不檢查跨線程訪問,允許各個線程操作UI元素,容易出現錯誤。
public Form2() { InitializeComponent(); //禁止對跨線程訪問做檢查 (不推薦使用這種方法) Control.CheckForIllegalCrossThreadCalls = false; }
2、使用委托方法 將其委托給UI控件更新
//使用委托方法 將其委托給UI控件更新 private void button1_Click(object sender, EventArgs e) { Thread thread1 = new Thread(new ParameterizedThreadStart(UpdateLabel2)); thread1.Start("更新Label"); } private void UpdateLabel2(object str) { if (label2.InvokeRequired) { // 當一個控件的InvokeRequired屬性值為真時,說明有一個創建它以外的線程想訪問它 Action<string> actionDelegate = (x) => { this.label2.Text = x.ToString(); }; // 或者 // Action<string> actionDelegate = delegate(string txt) { this.label2.Text = txt; }; this.label2.Invoke(actionDelegate, str); } else { this.label2.Text = str.ToString(); } }
3、使用delegate和BeginInvoke來從其他線程中控制控件
只要把上面的 this.label2.Invoke(actionDelegate, str); 中的 Invoke 改為BeginInvoke方法就可以了。
Invoke方法和BeginInvoke方法的區別是:Invoke方法是同步的, 它會等待工作線程完成,BeginInvoke方法是異步的, 它會另起一個線程去完成工作線。
4、使用同步上下文:SynchronizationContext方法
該方法是取得主線程的上下文信息,然后在子線程將訪問UI控件方法推送到UI上下文的消息隊列里,使用POST或者Send;
private SynchronizationContext synchronizationContext; private void button2_Click(object sender, EventArgs e) { synchronizationContext = SynchronizationContext.Current; new Thread(() => { UpdateText("跨線程訪問"); }).Start(); } void UpdateText(string msg) { synchronizationContext.Post(_ => this.label2.Text = msg, null); }
5、使用BackgroundWorker組件(推薦使用這個方法)
BackgroundWorker是.NET里面用來執行多線程任務的控件,它允許編程者在一個單獨的線程上執行一些操作。耗時的操作(如下載和數據庫事務)。
public partial class FileManagerForm : Form { FileInfo file ; BackgroundWorker bw; ServerFile server; public FileManagerForm(string filePath) { InitializeComponent(); file = new FileInfo(filePath); long size = file.Length / 1024 / 1024; lblOrgSize.Text = (int)size+ "MB"; bw = new BackgroundWorker(); server = new ServerFile(file.Name); } private void FileManagerForm_Load(object sender, EventArgs e) { proUpFile.Minimum = 0; proUpFile.Maximum = 100; bw.WorkerReportsProgress = true; bw.WorkerSupportsCancellation = true; bw.DoWork += Bw_DoWork; bw.ProgressChanged += Bw_ProgressChanged; bw.RunWorkerCompleted += Bw_RunWorkerCompleted; bw.RunWorkerAsync(); } private void Bw_DoWork(object sender, DoWorkEventArgs e) { using(FileStream fileRead= file.OpenRead()) { long setp = file.Length / 100; while (file.Length > fileRead.Position) { if (bw.CancellationPending) { break; } byte[] bytes = new byte[1024]; int count = fileRead.Read(bytes, 0, bytes.Length); long writeLength= server.UpFile(bytes, count); if(writeLength >proUpFile.Value* setp) { int size = (int)(writeLength / 1024 / 1024); bw.ReportProgress(proUpFile.Value + 1, size); } } server.Close(); } } private void Bw_ProgressChanged(object sender, ProgressChangedEventArgs e) { proUpFile.Value= e.ProgressPercentage> proUpFile.Maximum?proUpFile.Maximum:e.ProgressPercentage; lblUpLoadSize.Text = e.UserState.ToString() + "MB"; } private void Bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (this.proUpFile.Value == this.proUpFile.Maximum) { MessageBox.Show("文件發送成功!"); } else { MessageBox.Show("文件發送失敗!"); } this.Close(); } private void btnCancel_Click(object sender, EventArgs e) { bw.CancelAsync(); } }