BackgroundWorker 组件概述

有许多通常执行的操作可能需要很长时间才能完成。 例如:

  • 图像下载

  • Web 服务调用

  • 文件下载和上传(包括点对点应用程序)

  • 复杂的本地计算

  • 数据库事务

  • 本地磁盘访问,因为它相对于内存访问的速度较慢

这样的操作可能会导致用户界面在正在运行时阻塞。 需要响应式 UI 并且遇到与此类作相关的长时间延迟时,该 BackgroundWorker 组件提供了一个方便的解决方案。

BackgroundWorker 组件使你能够在不同于应用程序主 UI 线程的线程上异步执行耗时操作(即“在后台”)。 若要使用 a 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 类的详细信息,请参阅 How to: Run an Operation in the Background.

另请参阅