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);
    }
}

转载于:https://www.cnblogs.com/conexpress/p/WinForm_Thread_Operate_Control.html

猜你喜欢

转载自blog.csdn.net/weixin_33912453/article/details/93352531
今日推荐