C#中使用BackgroundWorker控件
在C#中,BackgroundWorker控件允许在单独的专用线程上运行操作。 耗时的操作(如下载和数据库事务)在长时间运行时可能会导致用户界面(UI)似乎处于停止响应状态。如果需要能进行响应的用户界面,而且面临与这类操作相关的长时间延迟,则可以使用BackgroundWorker类方便地解决问题。
以下代码有部分是项目中的业务代码,请选择性忽略
程序的执行步骤如下:
1.开始执行异步线程,进行后台操作,给后台传递参数
public void Connect() { if (this.backgroundWorker1.IsBusy) return; listBoxConnect.Items.Add(DateTime.Now.ToString() + " Start connection:Device connection in progress"); // RequestResult res = outService.PostConnect(new RequestConnect { }).Result; listBoxConnect.Items.Add(DateTime.Now.ToString() + " Start connection:Device connected successfully"); if (true) this.backgroundWorker1.RunWorkerAsync(10); //开启线程 } //执行线程任务 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { try { e.Result = this.ConnectWorker(this.backgroundWorker1, e); } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } }
2.进行后台任务执行,并获得任务结果
private bool ConnectWorker(BackgroundWorker backgroundWorker, DoWorkEventArgs e) { listBoxConnect.Items.Add(DateTime.Now.ToString() + " Start connection:Secs service starting"); if (_secsGem == null) { SECSConnect(); Thread.Sleep(3000); } listBoxConnect.Items.Add(DateTime.Now.ToString() + " Start connection:MES connection in progress"); int RepeatTimes = (int)e.Argument; for (int i = 0; i < RepeatTimes; i++) { if (backgroundWorker.CancellationPending) return false; if (bussService.SendS1F1().Code == "0") return true; else { listBoxConnect.Items.Add(DateTime.Now.ToString() + " Failed to send for the " + (i + 1) + " times"); Thread.Sleep(1000); } } return false; }
3.结束任务
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { try { if (!(bool)e.Result) //{ // labelStatus.Text = StatusEnum.ONLINE.ToString(); // listBoxConnect.Items.Add(DateTime.Now.ToString() + " Connection success"); //} //else { labelStatus.Text = StatusEnum.OFFLINE.ToString(); listBoxConnect.Items.Add(DateTime.Now.ToString() + " Connection failed,Transfer to OFFLINE state"); } listBoxConnect.Update(); } catch (TargetInvocationException ex) { MessageBox.Show(ex.InnerException.GetType().ToString()); } }
该控件也可与进度条控件等结合使用
参考文档:https://www.jb51.net/article/238684.htm
https://blog.csdn.net/u012563853/article/details/124042188
分类:
C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异