When WinForm program will encounter case by a background thread interface directly in a background thread execution method of direct access controls will complain, this time we should use indirect cross-thread operation controls. Here are two implementations.
1, using the delegate defined manner
private delegate void SetTextBoxValueDelegate(string value); private void SetTextBoxValue(string value) { if (this.txtInfo.InvokeRequired)//判断是否跨线程请求 { SetTextBoxValueDelegate myDelegate = delegate(string text) { txtInfo.Text = text; }; txtInfo.Invoke(myDelegate, value); } else { txtInfo.Text = value; } }
2, using Action <T> manner (recommended)
private void SetTextBoxValue(string value) { Action<string> setValueAction = text => txtInfo.Text = text;//Action<T>本身就是delegate类型,省掉了delegate的定义 if (this.txtInfo.InvokeRequired) { txtInfo.Invoke(setValueAction, value); } else { setValueAction(value); } }
Reproduced in: https: //www.cnblogs.com/conexpress/p/WinForm_Thread_Operate_Control.html