c#窗体 如何在backgroundworker的DoWork中结束这个后台?

BackgroundWorker的DoWork事件的委托签名如下:

  private void DoWork(object sender, DoWorkeventArgs e)

  其中参数e包含了大量信息,同时能够接收使用e.Cancel=true令worker取消任务。

  需要在DoWork中取消,应使用e.Cancel=true;return;

  需要在外部取消,应:

    1. 在初始化时令backgroundWorker1.WorkerReportsProgress = true;

    2. 在外部控制的地方(如按钮事件)backgroundWorker1.CancelAsync();

    3. CancelAsync会更改worker的CancellationPending标志,所以在DoWork中应有类似下面的片段判断并退出。 if(backgroundWorker1.CancellationPending) { e.Cancel=true; return;}

  最后,在DoWork退出后,如需在外部得知是何种原因导致结束(取消或完成),请在worker的RunWorkerCompleted事件中检查参数e.Cancel属性。

原文地址:https://www.cnblogs.com/12xiaole/p/7559947.html