您的位置:首页 > 编程语言 > C#

C#跨线程操作控件的线程安全方法

2009-05-06 09:38 232 查看
C#跨线程操作控件的线程安全方法

在C#中,经常用到这样一个场景,Windows Form程序启动一个工作者线程执行一部分工作,这样做是为了避免速度慢的工作如果直接调用会使得主Form停止响应一段时间。
既然启动了线程,就避免不了线程之间数据传递的事情,相信你有很多种办法能解决,总之注意同步和互斥操作就好。我想说的是,工作线程处理中可能想操作某个主线程的Windows Form的Control,比如按钮,ListView等等更新工作状态之类,直接控制是不行的,不能够跨线程操作另一个线程创建的Windows Form控件。要使用委托去调用。
01.using System;
02.using System.Collections.Generic;
03.using System.ComponentModel;
04.using System.Data;
05.using System.Drawing;
06.using System.Text;
07.using System.Windows.Forms;
08.using System.Threading;
09.
10.namespace JPGCompact
11.{
12. public partial class MainForm : Form
13. {
14. // 定义委托
15. private delegate void DelegateWriteResult(string file, bool result);
16.
17. // 与定义的委托签名相同的函数,操作主线程控件
18. private void WriteResult(string fileName, bool result)
19. {
20. if (result)
21. {
22. ListViewItem thisListItem = new ListViewItem();
23. thisListItem.ForeColor = Color.White;
24. thisListItem.BackColor = Color.DarkGreen;
25. thisListItem.SubItems[0].Text = fileName;
26. thisListItem.SubItems.Add("成功");
27. lvResultList.Items.Add(thisListItem);
28. }
29. else
30. {
31. ListViewItem thisListItem = new ListViewItem();
32. thisListItem.ForeColor = Color.White;
33. thisListItem.BackColor = Color.Red;
34. thisListItem.SubItems[0].Text = fileName;
35. thisListItem.SubItems.Add("失败");
36. lvResultList.Items.Add(thisListItem);
37. }
38. }
39.
40. // 启动线程
41. private void btnStart_Click(object sender, EventArgs e)
42. {
43. Thread workThread = new Thread(new ThreadStart(CompressAll));
44. // 设置为背景线程,主线程一旦推出,该线程也不等待而立即结束
45. workThread.IsBackground = true;
46. workThread.Start();
47. }
48.
49. // 线程执行函数
50. private void CompressAll()
51. {
52. // 判断是否需要Invoke,多线程时需要
53. if (this.InvokeRequired)
54. {
55. // 通过委托调用写主线程控件的程序,传递参数放在object数组中
56. this.Invoke(new DelegateWriteResult(WriteResult),
57. new object[] { item, true });
58. }
59. else
60. {
61. // 如果不需要委托调用,则直接调用
62. this.WriteResult(item, true);
63. }
64. }
65. }
66.}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: