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

在我们写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";
            }
        }
    }
}


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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值