runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

if (this.InvokeRequired)
this.Invoke(new MethodInvoker(() => { this.Close(); }));
else
this.Close();

 

重点:

if (this.InvokeRequired) 用来判断是否后台线程来修改UI线程。如果是:使用this.Invoke来修改UI线程上的控件。

 

this.Invoke 同步修改UI。this.BeginInvoke 异步修改UI。看情况选用哪个。

 

完整方法:

/// <summary>
        /// 异步中弹出对话框MessageBox
        /// </summary>
        /// <param name="curMsg"></param>
        void InvokeMsgBox(string curMsg)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MethodInvoker(() =>
                {
                    MessageBox.Show(curMsg);
                }));
            }
            else
            {
                MessageBox.Show(curMsg);
            }
        }

MethodInvoker,也可以换成 Action.


简化写法:
private void btnUI_Click(object sender, EventArgs e)
        {
            changeUI("UI消息1", "UI消息2");
        }

        private void btnFUI_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                changeUI("非UI消息1", "非UI消息2");
            });
        }

        void changeUI(string msg1, string msg2)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MethodInvoker(() =>
                {
                    changeUI(msg1, msg2);
                }));
            }
            else
            {
                MessageBox.Show(msg1);
                lblMsg2.Text = msg2;
            }
        }

 


-
posted on 2017-01-06 17:32  runliuv  阅读(216)  评论(0编辑  收藏  举报