Winform中如何跨線程訪問UI元素
在C# 的應(yīng)用程序開發(fā)中, 我們經(jīng)常要把UI線程和工作線程分開,防止界面停止響應(yīng), 同時(shí)我們又需要在工作線程中更新UI界面上的控件。但直接訪問會(huì)出現(xiàn)“線程間操作無效”的情況,因?yàn)?NET禁止了跨線程調(diào)用控件, 否則誰都可以操作控件,最后可能造成錯(cuò)誤。 下面介紹幾種跨線程訪問的方法:
1、禁止對(duì)跨線程訪問做檢查 (不推薦使用這種方法)
這種方法不檢查跨線程訪問,允許各個(gè)線程操作UI元素,容易出現(xiàn)錯(cuò)誤。
public Form2() { InitializeComponent(); //禁止對(duì)跨線程訪問做檢查 (不推薦使用這種方法) 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) { // 當(dāng)一個(gè)控件的InvokeRequired屬性值為真時(shí),說明有一個(gè)創(chuàng)建它以外的線程想訪問它 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方法的區(qū)別是:Invoke方法是同步的, 它會(huì)等待工作線程完成,BeginInvoke方法是異步的, 它會(huì)另起一個(gè)線程去完成工作線。
4、使用同步上下文:SynchronizationContext方法
該方法是取得主線程的上下文信息,然后在子線程將訪問UI控件方法推送到UI上下文的消息隊(duì)列里,使用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組件(推薦使用這個(gè)方法)
BackgroundWorker是.NET里面用來執(zhí)行多線程任務(wù)的控件,它允許編程者在一個(gè)單獨(dú)的線程上執(zhí)行一些操作。耗時(shí)的操作(如下載和數(shù)據(jù)庫事務(wù))。
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("文件發(fā)送成功!"); } else { MessageBox.Show("文件發(fā)送失?。?); } this.Close(); } private void btnCancel_Click(object sender, EventArgs e) { bw.CancelAsync(); } }
以上就是Winform中如何跨線程訪問UI元素的詳細(xì)內(nèi)容,更多關(guān)于Winform 訪問UI元素的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- C#之WinForm跨線程訪問控件實(shí)例
- Winform跨線程操作的簡單方法
- 淺談C#跨線程調(diào)用窗體控件(比如TextBox)引發(fā)的線程安全問題
- C#多線程與跨線程訪問界面控件的方法
- C#實(shí)現(xiàn)跨線程操作控件方法
- C#中跨線程訪問控件問題解決方案分享
- 在Winform程序中使用Spire.Pdf實(shí)現(xiàn)頁面添加印章功能的實(shí)現(xiàn)
- C# Winform中如何繪制動(dòng)畫示例詳解
- C# Winform調(diào)用百度接口實(shí)現(xiàn)人臉識(shí)別教程(附源碼)
- visual studio 2019使用net core3.0創(chuàng)建winform無法使用窗體設(shè)計(jì)器
相關(guān)文章
C#使用SQL DataAdapter數(shù)據(jù)適配代碼實(shí)例
今天小編就為大家分享一篇關(guān)于C#使用SQL DataAdapter數(shù)據(jù)適配代碼實(shí)例,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-10-10c# 閉包的相關(guān)知識(shí)以及需要注意的地方
這篇文章主要介紹了c# 閉包的相關(guān)知識(shí)以及需要注意的地方,文中講解非常細(xì)致,代碼幫助大家理解和學(xué)習(xí),感興趣的朋友可以參考下2020-06-06C#操作Clipboard讀取剪切板中數(shù)據(jù)實(shí)例詳解
這篇文章主要介紹了C#操作Clipboard讀取剪切板中數(shù)據(jù)的方法,實(shí)例分析了C#讀取剪貼板數(shù)據(jù)的具體步驟與實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-05-05C#基礎(chǔ)語法:結(jié)構(gòu)和類區(qū)別詳解
這篇文章主要介紹了C#基礎(chǔ)語法:結(jié)構(gòu)和類詳解,本文總結(jié)了一些結(jié)構(gòu)和類的不同之處并給出了測(cè)試區(qū)別特性代碼,需要的朋友可以參考下2015-06-06