BackgroundWorker与DoWorkEventArgs详解

发布时间 2023-05-29 15:38:59作者: 退退退退下吧
在学习公司给的项目过程中遇到了一些不懂得地方,在此记录下来。

1、BackgroundWorker(在单独的线程上执行操作)

首先在Microsoft学习BackgroundWorker基础知识,了解目标属性与方法。

BackgroundWorker 类 (System.ComponentModel) | Microsoft Learn

下面是一些对我有帮助的文章,在此贴出来方便学习。
C# BackgroundWorker 详解 - sparkdev - 博客园 (cnblogs.com)

2、DoWorkEventArgs 类(为 DoWork 事件处理程序提供数据)

DoWorkEventArgs 类 (System.ComponentModel) | Microsoft Learn

下面的代码示例演示如何使用 DoWorkEventArgs 类来处理 DoWork 事件。

 1 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
 2 {
 3     // Do not access the form's BackgroundWorker reference directly.
 4     // Instead, use the reference provided by the sender parameter.
 5     BackgroundWorker bw = sender as BackgroundWorker;
 6 
 7     // Extract the argument.
 8     int arg = (int)e.Argument;
 9 
10     // Start the time-consuming operation.
11     e.Result = TimeConsumingOperation(bw, arg);
12 
13     // If the operation was canceled by the user, 
14     // set the DoWorkEventArgs.Cancel property to true.
15     if (bw.CancellationPending)
16     {
17         e.Cancel = true;
18     }
19 }

 

  1. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e):定义了一个名为 backgroundWorker1_DoWork 的方法,该方法是 BackgroundWorkerDoWork 事件的处理方法。DoWork 事件在后台执行长时间运行的操作。

    • sender:事件的发送者,通常是 BackgroundWorker 对象本身。
    • e:包含事件数据的 DoWorkEventArgs 对象,可以通过它访问传递给事件处理方法的参数,并设置操作的结果或取消标志。
  2. BackgroundWorker bw = sender as BackgroundWorker;:将 sender 强制转换为 BackgroundWorker 对象,并赋值给 bw 变量。这样可以访问 BackgroundWorker 对象的属性和方法。

  3. int arg = (int)e.Argument;:从 DoWorkEventArgs 对象的 Argument 属性中提取传递给事件处理方法的参数,并将其强制转换为整数类型,并赋值给 arg 变量。这样可以在后台操作中使用传递的参数。

  4. e.Result = TimeConsumingOperation(bw, arg);:调用名为 TimeConsumingOperation 的方法来执行耗时的操作,并将操作的结果赋值给 DoWorkEventArgs 对象的 Result 属性。这样可以在后台操作完成后获取结果。

  5. if (bw.CancellationPending):检查 BackgroundWorker 对象的 CancellationPending 属性,判断操作是否被用户取消。

      • 如果 CancellationPendingtrue,则将 DoWorkEventArgs 对象的 Cancel 属性设置为 true,表示操作被取消。
      • 如果 CancellationPendingfalse,则继续执行后台操作。
     

仅为学习记录文章,如有冒犯请联系我!