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 }
-
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e):定义了一个名为backgroundWorker1_DoWork的方法,该方法是BackgroundWorker的DoWork事件的处理方法。DoWork事件在后台执行长时间运行的操作。sender:事件的发送者,通常是BackgroundWorker对象本身。e:包含事件数据的DoWorkEventArgs对象,可以通过它访问传递给事件处理方法的参数,并设置操作的结果或取消标志。
-
BackgroundWorker bw = sender as BackgroundWorker;:将sender强制转换为BackgroundWorker对象,并赋值给bw变量。这样可以访问BackgroundWorker对象的属性和方法。 -
int arg = (int)e.Argument;:从DoWorkEventArgs对象的Argument属性中提取传递给事件处理方法的参数,并将其强制转换为整数类型,并赋值给arg变量。这样可以在后台操作中使用传递的参数。 -
e.Result = TimeConsumingOperation(bw, arg);:调用名为TimeConsumingOperation的方法来执行耗时的操作,并将操作的结果赋值给DoWorkEventArgs对象的Result属性。这样可以在后台操作完成后获取结果。 -
if (bw.CancellationPending):检查BackgroundWorker对象的CancellationPending属性,判断操作是否被用户取消。- 如果
CancellationPending为true,则将DoWorkEventArgs对象的Cancel属性设置为true,表示操作被取消。 - 如果
CancellationPending为false,则继续执行后台操作。
- 如果
仅为学习记录文章,如有冒犯请联系我!