C# WinForm BackgroundWorker
前言
在C#的WinForm程序中,有的时候我们会需要一些耗时比较长的操作,比如拷贝文件,下载大文件,或者其他什么耗时比较长的操作,这个时候如果把这些操作都放在主线程(UI线程)中,那么就会造成主线程需要先将耗时操作完成再响应界面的问题。
需求说明
假设我们目前有如下的界面,界面上两个按钮Button
,一个文本框TextBox
,一个标签Label
和一个进度条ProgressBar
。现在有如下的要求,当我们点下Start时,从1~100令进度条开始填充。然后标签可以实时显示进度条的值。
代码部分如下,很简单的功能。
private void btnStart_Click(object sender, EventArgs e)
{
for (int i = 0; i < 100; i++)
{
pgbTest.PerformStep();
lblTest.Text = pgbTest.Value.ToString();
Thread.Sleep(200);//这里我们每次循环时等待200毫秒来模拟耗时操作。
}
}
运行预览
可以看到效果没有达到预期的那样,同时在进度条填充的过程中其他控件也无法操作。用平常的话说就会变得很“卡”。这种时候就会一般就会用到多线程来解决。但是其实微软已经很贴心的为我们封装好了一个组件,那不如直接来用一下。
BackgroundWorker
简介
引用微软官方文档中的注释:
The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.
To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.
渣翻见谅:
BackgroundWorker
类允许用户在专门且独立于主线程的线程上进行操作。当用户执行一些类似下载或者数据库事物的耗时操作时,可能会让界面UI产生类似停止响应的现象。当用户需要执行类似的耗时操作,且同时需要界面UI及时响应时,BackgroundWorker
类提供了一个十分便捷的解决方案。
要执行一个后台操作,可以注册DoWork
事件,并在此事件中实现耗时操作。然后,如果想要开始任务,可以调用RunWorkAsync
方法。如希望接收进度变化提示,可以注册ProgressChanged
事件。如希望在操作完成时接收提示,可以注册