C#中跨线程更新UI简单方法

jsper / 2023-07-30 / 原文

.NET3.5中,C# winform 无法直接在子线程中更新UI组件的属性,会报“更新UI的线程非UI组件的创建线程”的错误,需要用到委托更新。

有两种方式:

方式1:

            string test = "测试...";
                    this.BeginInvoke(
                        (Action)delegate()
                        {
                            this.labelStatus.Text = test;
                            this.buttonStart.Enabled = true;
                            this.buttonFileSelect.Enabled = true;
                            this.textBoxServerIP.ReadOnly = false;
                            this.progressBar.Value = 0;
                            this.labelProgress.Text = "0%";
                        }
                    );

 

方式2:

// 先声明一个委托
delegate void updateLableStatusTextDelegate(string text);

// 实现委托功能
private void updateLableStatusText(string text)
{
    this.labelStatus.Text = text;
}


// 执行委托调用
this.BeginInvoke(new updateLableStatusTextDelegate(updateLableStatusText), "测试...");