当构建一个图形化的Windows Form桌面应用程序并且需要执行在应用程序主UI线程之外的线程中长时间的任务时,BackgroundWorker类就很有用了。
要使用BackgroundWorker,我们只需要告诉它希望在后台执行那个方法并且调用RunWorkerAsync()即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click( object sender, EventArgs e) { int a = int .Parse(textBox1.Text.Trim()); int b = int .Parse(textBox2.Text.Trim()); Add ad = new Add(a,b); backgroundWorker1.RunWorkerAsync(ad); } private void backgroundWorker1_DoWork( object sender, DoWorkEventArgs e) { Add args = (Add)e.Argument; for ( int i = 0 ; i < 11 ; i + + ) { Thread.Sleep( 200 ); backgroundWorker1.ReportProgress(i * 10 ); } e.Result = args.a + args.b; } private void backgroundWorker1_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { label1.Text = e.Result.ToString(); } private void backgroundWorker1_ProgressChanged( object sender, ProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; } } public class Add { public int a; public int b; public Add( int a, int b) { this.a = a; this.b = b; } } |
以上就是c# BackgroundWorker组件的作用的详细内容,更多关于c# BackgroundWorker组件的资料请关注服务器之家其它相关文章!
原文链接:https://www.cnblogs.com/wangzhenghua/p/4448752.html