C# 子线程中更新UI界面

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        void UpdateUI(string msg)
        {
            //添加消息
            text_Msg.Text += msg;
            //滚动条到底部
            text_Msg.SelectionStart = text_Msg.Text.Length;
            text_Msg.ScrollToCaret();
        }

        void UpdateUIAll(string msg)
        {
            //查看当前调用本函数的线程
            string threadId = Thread.CurrentThread.ManagedThreadId.ToString();
            if (this.InvokeRequired)   //判断是否为主线程在调用(不是主线程则将方法需要注入到主线程)
            {
                //不是主线程调用,将函数注入到主线程 
                //(另:Invoke 与begininvoke区别在于:invoke会阻塞当前线程,直到invoke调用结束,才会继续执行下去,
                //  而begininvoke 则可以异步进行调用,也就是该方法封送完毕后马上返回,不会等待委托方法的执行结束,调用者线程将不会被阻塞。)
                this.Invoke(          
                    new Action(() =>   //创建一个用来更新UI的委托
                    {
                        UpdateUI(threadId+",非主线程更新:" +msg);  //更新UI的函数
                    })
                );
            }
            else
            {
                //是主线程调用,直接调用函数
                UpdateUI(threadId+",主线程更新:" +msg);   //更新UI的函数
            }
        }
        private void btn_delegate_Click(object sender, EventArgs e)
        {
            //测试效果
            string msg = "你好!\r\n";
            UpdateUIAll(msg); 
            Thread thread = new Thread(
                new ThreadStart(
                    new Action(()=> {
                        UpdateUIAll(msg);
                    })
                )
            );
            thread.Start();
        }
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值