BackgroundWorker 组件概述
有许多通常执行的操作可能需要很长时间才能执行。 例如:
图片下载
Web 服务调用
文件下载和上传(包括点对点应用程序)
复杂的本地计算
数据库事务
本地磁盘访问,因为它相对于内存访问的速度较慢
这些操作可能会导致用户界面在操作时卡住。 需要响应式 UI 并且遇到与此类操作相关的长时间延迟时,BackgroundWorker 组件提供了一个方便的解决方案。
BackgroundWorker 组件使你能够在不同于应用程序主 UI 线程的线程上异步执行耗时的操作(“在后台)。 若要使用 BackgroundWorker,只需指定要在后台执行的耗时工作方法,然后调用 RunWorkerAsync 方法。 调用线程在工作方法异步运行时继续正常运行。 方法完成后,BackgroundWorker 通过触发 RunWorkerCompleted 事件来警报调用线程,该事件可以选择包含操作的结果。
BackgroundWorker 组件可从“组件”选项卡中的 工具箱中获取。若要向窗体添加 BackgroundWorker,请将 BackgroundWorker 组件拖到窗体上。 它显示在组件托盘中,其属性显示在 属性 窗口中。
若要启动异步操作,请使用 RunWorkerAsync 方法。 RunWorkerAsync 采用可选的 object
参数,该参数可用于传递参数给工作方法。 BackgroundWorker 类公开了 DoWork 事件,您的工作线程通过 DoWork 事件处理程序附加到该事件上。
DoWork 事件处理程序接受一个 DoWorkEventArgs 参数,该参数具有一个 Argument 属性。 此属性从 RunWorkerAsync 接收参数,并可以传递给你的工作方法,该方法将在 DoWork 事件处理程序中调用。 以下示例演示如何从名为 ComputeFibonacci
的工作方法中将结果进行分配。 它是一个更大示例的一部分,您可以在 如何:实现使用后台操作的窗体中找到。
// This event handler is where the actual,
// potentially time-consuming work is done.
void backgroundWorker1_DoWork( Object^ sender, DoWorkEventArgs^ e )
{
// Get the BackgroundWorker that raised this event.
BackgroundWorker^ worker = dynamic_cast<BackgroundWorker^>(sender);
// Assign the result of the computation
// to the Result property of the DoWorkEventArgs
// object. This is will be available to the
// RunWorkerCompleted eventhandler.
e->Result = ComputeFibonacci( safe_cast<Int32>(e->Argument), worker, e );
}
// This event handler is where the actual,
// potentially time-consuming work is done.
private void backgroundWorker1_DoWork(object sender,
DoWorkEventArgs e)
{
// Get the BackgroundWorker that raised this event.
BackgroundWorker worker = sender as BackgroundWorker;
// Assign the result of the computation
// to the Result property of the DoWorkEventArgs
// object. This is will be available to the
// RunWorkerCompleted eventhandler.
e.Result = ComputeFibonacci((int)e.Argument, worker, e);
}
' This event handler is where the actual work is done.
Private Sub backgroundWorker1_DoWork( _
ByVal sender As Object, _
ByVal e As DoWorkEventArgs) _
Handles backgroundWorker1.DoWork
' Get the BackgroundWorker object that raised this event.
Dim worker As BackgroundWorker = _
CType(sender, BackgroundWorker)
' Assign the result of the computation
' to the Result property of the DoWorkEventArgs
' object. This is will be available to the
' RunWorkerCompleted eventhandler.
e.Result = ComputeFibonacci(e.Argument, worker, e)
End Sub
有关使用事件处理程序的详细信息,请参阅 事件。
谨慎
在使用任何类型的多线程时,您可能会将自己暴露在非常严重和复杂的错误中。 在实现使用多线程处理的任何解决方案之前,请参阅 托管线程处理最佳做法。
有关使用 BackgroundWorker 类的详细信息,请参阅 如何:在后台中运行操作。