Visual studio之C#跨线程调用UI控件

背景

当前串口通讯项目,多个线程需要同时利用richTextBoxMsg控件打印信息,直接调用会造成线程不安全,严重的时候会直接导致UI线程挂掉,因此本篇就跨线程调用UI控件做个记录。

正文

  • 定义控件的委托类型
// 提示界面控件的委托类型
delegate void ShowInfoCallback(string text, bool handle);
  • 定义操作该控件的函数
//该函数会在非创建UI控件的线程调用下,进行委托,由UI线程进行操作UI控件;
//若该函数由创建该UI控件的线程调用,则直接进行操作。
// handle 为 true,则为控件使用.text;为false,则控件使用.Appendtext
private void Showinfo(string text, bool handle)
{
        if (this.richTextBoxMsg.InvokeRequired)
        {   //若是创建控件的线程与调用该函数的线程不是同一个线程则进入
            while (!this.richTextBoxMsg.IsHandleCreated)
            {
                if (this.richTextBoxMsg.Disposing || this.richTextBoxMsg.IsDisposed)
                {// 解决窗体关闭时出现“访问已释放句柄的异常”
                    return;
                }
             }
             ShowInfoCallback d = new ShowInfoCallback(Showinfo);
             this.richTextBoxMsg.Invoke(d, new object[] { text, handle });
        }
        else
        {
            if(handle == true)
            {
                this.richTextBoxMsg.Text = text;
            }
            else
            {
                this.richTextBoxMsg.AppendText(text);
             }
                
        }
}
  • 调用方法
    直接调用即可。

至此记录完毕。

参考链接

记录时间:2017-05-25
记录地点:江苏淮安

posted @ 2017-05-25 11:14  Ch_Y_Q  阅读(1614)  评论(0编辑  收藏  举报