编写应用程序时,涉及到大量数据处理、串口通讯、Socket通讯等都会用到多线程,多线程中如何跨线程调用主界面或其余界面下的控件是一个问题,利用invoke和delegate能够解决。多线程
delegate其实就是函数的指针,invoke是控件的唤醒函数。函数
//跨线程设置控件comboBox的值 public delegate void commbdelegate(ComboBox cb); public void commb(ComboBox cb) { if (cb.InvokeRequired) { commbdelegate dt = new commbdelegate(commb); cb.Invoke(dt, new object[]{cb}); } else { cb.Text = "test"; } }
状况二:函数须要返回值ui
//跨线程读取控件ComboBox的值,并返回 public delegate string commbdelegate(ComboBox cb); public string commb(ComboBox cb) { if (cb.InvokeRequired) { commbdelegate dt = new commbdelegate(commb); IAsyncResult ia=cb.BeginInvoke(dt, new object[]{cb}); return (string)cb.EndInvoke(ia); //这里须要利用EndInvoke来获取返回值 } else { return cb.Text; } }