线程UI同步
只用一次:
this.Invoke(new MethodInvoker(() => { this.btnGo.Enabled = true; MessageBox.Show("Yeah ! "); }));
或
Invoke(new Action( () => { this.button2.Text = "bbb"; }) );
譬如设置控件的文本, 可以统一封装
private void SetControlText2(Control c, string text) { if (c.InvokeRequired) { this.Invoke(new MethodInvoker(delegate() { SetControlText2(c, text); }), c, text); } else { c.Text = text; ; } }
上面这是简易的写法,要写成下面这种也可以;
private delegate void SetControlTextCallBack(Control c, string text); private void SetControlText(Control c,string text) { if (c.InvokeRequired) { this.Invoke(new SetControlTextCallBack(SetControlText), c,text); } else { c.Text = text; ; // btnTest.Text =bool( o); } }
使用Action写法:
private Action<Control, string> SetText; //赋值: SetText = (c, s) => { if (this.InvokeRequired) { Invoke(SetText,c,s); } else { c.Text = s; } }; //调用: ThreadStart t = new ThreadStart(() => { SetText(button2, "aaa"); });