BackgroundWorker与DoWorkEventArgs详解
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
,则继续执行后台操作。
- 如果
仅为学习记录文章,如有冒犯请联系我!
本文作者:kai-liang
本文链接:https://www.cnblogs.com/kai-liang/p/17440627.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步