多线程程序中线程安全的操纵可视化控件

来源:互联网 发布:java 数组切片 编辑:程序博客网 时间:2024/04/30 11:08

在我们写WinForm程序的时候,如果在新创建的另外一个线程中直接操纵界面的可视化控件,会提示错误。如下提示:

线程间操作无效: 从不是创建控件“richTextBox1”的线程访问它。

 

代码如下所示,当没有从线程中操作可视化控件的时候,代码是安全的。

namespace SafeThread{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button2_Click(object sender, EventArgs e)        {            this.richTextBox1.Text += "add message through main thread!\n";        }        //private void button1_Click(object sender, EventArgs e)        //{        //    Thread thread = new Thread(new ThreadStart(addMsg));        //    thread.IsBackground = true;        //    thread.Start();        //}        //private void addMsg()        //{        //    this.richTextBox1.Text += "add message through other thread!\n";        //}    }}


但是当另外一个按钮从其他的线程直接操作可视化控件以后,就会提示错误的操作:代码如下:

namespace SafeThread{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button2_Click(object sender, EventArgs e)        {            this.richTextBox1.Text += "add message through main thread!\n";        }        private void button1_Click(object sender, EventArgs e)        {            Thread thread = new Thread(new ThreadStart(addMsg));            thread.IsBackground = true;            thread.Start();        }        private void addMsg()        {            this.richTextBox1.Text += "add message through other thread!\n";        }    }}


这其中的原因,在于windows窗体编程的消息机制,windows维持一个给窗体传递的消息列表,记录每个事件消息发送给了每个可视化控件,系统单独的为消息列表维护了一个线程,并且这个消息列表属于队列,先进先出。如果从自己添加的线程中给可视化控件传递消息,则会打乱系统的消息列表,所以是系统不允许的。但是我们又需要在多线程中操作可视化控件,怎么办呢?可以用委托和反射来实现。

实现的代码并不复杂,只要对每个可视化控件的操作添加一个委托就可以了。

一种实现的代码如下所示:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Threading;namespace SafeThread{    public partial class Form1 : Form    {        private delegate void callRichTextBox(string s);        public Form1()        {            InitializeComponent();        }        private void button2_Click(object sender, EventArgs e)        {            this.richTextBox1.Text += "add message through main thread!\n";        }        private void button1_Click(object sender, EventArgs e)        {            Thread thread = new Thread(new ParameterizedThreadStart(addMsg));            thread.IsBackground = true;            thread.Start("add message through other thread!");        }        private void addMsg(object log)        {            if (richTextBox1.InvokeRequired)            {                callRichTextBox call = delegate(string s) { this.richTextBox1.Text += s + "\n"; };                // 下面调用的Invoke()函数,如果委托有参数,则第二个参数则为委托的参数                this.richTextBox1.Invoke(call, log);            }            else            {                this.richTextBox1.Text += "add message through other thread!\n";            }        }    }}


 

测试表明,程序运行正常。

上面使用了显示定义的委托,也可以通过下面这种方法来定义委托,这里使用了C# 系统已经定义好的一种委托Action<>:

namespace SafeThread{    public partial class Form1 : Form    {        //private delegate void callRichTextBox(string s);        public Form1()        {            InitializeComponent();        }        private void button2_Click(object sender, EventArgs e)        {            this.richTextBox1.Text += "add message through main thread!\n";        }        private void button1_Click(object sender, EventArgs e)        {            Thread thread = new Thread(new ParameterizedThreadStart(addMsg));            thread.IsBackground = true;            thread.Start("add message through other thread!");        }        private void addMsg(object log)        {            if (richTextBox1.InvokeRequired)            {                //callRichTextBox call = delegate(string s) { this.richTextBox1.Text += s + "\n"; };                Action<string> call = delegate(string t) { this.richTextBox1.Text += t + "\n"; };                // 下面调用的Invoke()函数,如果委托有参数,则第二个参数则为委托的参数                this.richTextBox1.Invoke(call, log);            }            else            {                this.richTextBox1.Text += "add message through other thread!\n";            }        }    }}


同样程序运行正常,这里比较简单,所以就不给出用户界面截图了。

原创粉丝点击