详情介绍c#中Winform实现多线程异步更新UI的示例代码


当前第2页 返回上一页

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

private void btnWrite_Click(object sender, EventArgs e)

{

 int taskCount = 10000; //任务量为10000

 this.pgbWrite.Maximum = taskCount;

 this.pgbWrite.Value = 0;

 

 DataWrite dataWrite = new DataWrite();//实例化一个写入数据的类

 dataWrite.UpdateUIDelegate += UpdataUIStatus;//绑定更新任务状态的委托

 dataWrite.TaskCallBack += Accomplish;//绑定完成任务要调用的委托

 

 Thread thread = new Thread(new ParameterizedThreadStart(dataWrite.Write));

 thread.IsBackground = true;

 thread.Start(taskCount);

}

 

//更新UI

private void UpdataUIStatus(int step)

{

 if (InvokeRequired)

 {

  this.Invoke(new AsynUpdateUI(delegate(int s)

  {

   this.pgbWrite.Value += s;

   this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();

  }), step);

 }

 else

 {

  this.pgbWrite.Value += step;

  this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();

 }

}

 

//完成任务时需要调用

private void Accomplish()

{

 //还可以进行其他的一些完任务完成之后的逻辑处理

 MessageBox.Show("任务完成");

}

效果如下:

总结

实现异步更新ui有很多种方法,但是我认为这种方式是比较灵活,能实时的获取到任务进行的状态,并且对之进行相应的处理。这种模式还适用于使用多个线程同时写入不同的数据到不同的文件中去。

以上就是详情介绍c#中Winform实现多线程异步更新UI的示例代码的详细内容!

返回前面的内容

相关阅读 >>

.net(C#)输入域名获取主域名小工具

C#实现char字符数组与字符串相互转换的方法详解

C#解析xml文件的代码实例分享

C# 7.0 语言新特性

C#中的console是什么意思

C#如何防止sql注入?

不用ide也能写出C#的hello world详解(图)

C#中@用法的实例解析

使用C#给pdf文档添加注释的示例代码分享(图)

C#实现一个简单的http服务器

更多相关阅读请进入《C#》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...