WinForm中跨線程操作控件
在WinForm編程時會遇到通過后臺線程操作界面的情況,直接在后臺線程執行的方法中直接操作控件會報錯,這時候就要使用跨線程方式間接操作控件。下面是兩種實現方式。
1、采用定義delegate的方式
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、采用Action<T>的方式(推薦)
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); } }
Author:Alex Leo
Email:conexpress@qq.com
Blog:http://conexpress.cnblogs.com/

浙公網安備 33010602011771號