BackgroundWorker

有关如何使用 BackgroundWorker 对象在后台线程中执行时间密集型操作的简单示例,请参见下文。

你需要:

  1. 定义一个执行时间密集型工作的 worker 方法,并从 BackgroundWorkerDoWork 事件的事件处理程序中调用它。
  2. RunWorkerAsync 开始执行。附加到 DoWork 的 worker 方法所需的任何参数都可以通过 DoWorkEventArgs 参数传递给 RunWorkerAsync

除了 DoWork 事件之外,BackgroundWorker 类还定义了两个应该用于与用户界面交互的事件。这些是可选的。

  • DoWork 处理程序完成时会触发 RunWorkerCompleted 事件。
  • 调用 ReportProgress 方法时会触发 ProgressChanged 事件。
public void ProcessDataAsync()
{
    // Start the time intensive method
    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += BwDoWork;
    bw.RunWorkerCompleted += BwRunWorkerCompleted;
    bw.RunWorkerAsync(@"PATH_TO_SOME_FILE");

    // Control returns here before TimeintensiveMethod returns
    Console.WriteLine("You can read this while TimeintensiveMethod is still running.");
}

// Method that will be called after BwDoWork exits
private void BwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // we can access possible return values of our Method via the Parameter e
    Console.WriteLine("Count: " + e.Result);
}

// execution of our time intensive Method
private void BwDoWork(object sender, DoWorkEventArgs e)
{
    e.Result = TimeintensiveMethod(e.Argument);
}

private int TimeintensiveMethod(object file)
{
    Console.WriteLine("Start TimeintensiveMethod.");

    // Do some time intensive calculations...
    using (StreamReader reader = new StreamReader(file.ToString()))
    {
        string s = reader.ReadToEnd();

       for (int i = 0; i < 10000; i++)
            s.GetHashCode();
    }
    Console.WriteLine("End TimeintensiveMethod.");

    // return something as a "result"
    return new Random().Next(100);
}