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

.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), "测试...");
复制代码

 

posted @   jsper  阅读(585)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示