对 Windows 窗体控件进行线程安全调用

c#如何对 Windows 窗体控件进行线程安全调用 今天在编写c#的windows窗体程序的时候,需要用到线程来控制一个 阅读详情

访问 Windows 窗体控件本质上不是线程安全的。如果有两个或多个线程操作某一控件的状态,则可能会迫使该控件进入一种不一致的状态。还可能出现其他与线程相关的 bug,包括争用情况和死锁。确保以线程安全方式访问控件非常重要。

.NET Framework 有助于在以非线程安全方式访问控件时检测到这一问题。在调试器中运行应用程序时,如果创建某控件的线程之外的其他线程试图调用该控件,则调试器会引发一个 InvalidOperationException,并提示消息:“从不是创建控件 control name 的线程访问它。”

此异常在调试期间和运行时的某些情况下可靠地发生。强烈建议您在显示此错误信息时修复此问题。在调试以 .NET Framework 2.0 版之前的 .NET Framework 编写的应用程序时,可能会出现此异常。

Note注意

可以通过将 CheckForIllegalCrossThreadCalls 属性的值设置为 false 来禁用此异常。这会使控件以与在 Visual Studio 2003 下相同的方式运行。

下面的代码示例演示如何从辅助线程以线程安全方式和非线程安全方式调用 Windows 窗体控件。它演示一种以非线程安全方式设置 TextBox 控件的 Text 属性的方法,还演示两种以线程安全方式设置 Text 属性的方法。

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace CrossThreadDemo
{
    public class Form1 : Form
    {
        // This delegate enables asynchronous calls for setting
        // the text property on a TextBox control.
        delegate void SetTextCallback(string text);

        // This thread is used to demonstrate both thread-safe and
        // unsafe ways to call a Windows Forms control.
        private Thread demoThread = null;

        // This BackgroundWorker is used to demonstrate the 
        // preferred way of performing asynchronous operations.
        private BackgroundWorker backgroundWorker1;

        private TextBox textBox1;
        private Button setTextUnsafeBtn;
        private Button setTextSafeBtn;
        private Button setTextBackgroundWorkerBtn;

        private System.ComponentModel.IContainer components = null;

        public Form1()
        {
            InitializeComponent();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        // This event handler creates a thread that calls a 
        // Windows Forms control in an unsafe way.
        private void setTextUnsafeBtn_Click(
            object sender, 
            EventArgs e)
        {
            this.demoThread = 
                new Thread(new ThreadStart(this.ThreadProcUnsafe));

            this.demoThread.Start();
        }

        // This method is executed on the worker thread and makes
        // an unsafe call on the TextBox control.
        private void ThreadProcUnsafe()
        {
            this.textBox1.Text = "This text was set unsafely.";
        }

        // This event handler creates a thread that calls a 
        // Windows Forms control in a thread-safe way.
        private void setTextSafeBtn_Click(
            object sender, 
            EventArgs e)
        {
            this.demoThread = 
                new Thread(new ThreadStart(this.ThreadProcSafe));

            this.demoThread.Start();
        }

        // This method is executed on the worker thread and makes
        // a thread-safe call on the TextBox control.
        private void ThreadProcSafe()
        {
            this.SetText("This text was set safely.");
        }

        // This method demonstrates a pattern for making thread-safe
        // calls on a Windows Forms control. 
        //
        // If the calling thread is different from the thread that
        // created the TextBox control, this method creates a
        // SetTextCallback and calls itself asynchronously using the
        // Invoke method.
        //
        // If the calling thread is the same as the thread that created
        // the TextBox control, the Text property is set directly. 

        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)
            {    
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.textBox1.Text = text;
            }
        }

        // This event handler starts the form's 
        // BackgroundWorker by calling RunWorkerAsync.
        //
        // The Text property of the TextBox control is set
        // when the BackgroundWorker raises the RunWorkerCompleted
        // event.
        private void setTextBackgroundWorkerBtn_Click(
            object sender, 
            EventArgs e)
        {
            this.backgroundWorker1.RunWorkerAsync();
        }
        
        // This event handler sets the Text property of the TextBox
        // control. It is called on the thread that created the 
        // TextBox control, so the call is thread-safe.
        //
        // BackgroundWorker is the preferred way to perform asynchronous
        // operations.

        private void backgroundWorker1_RunWorkerCompleted(
            object sender, 
            RunWorkerCompletedEventArgs e)
        {
            this.textBox1.Text = 
                "This text was set safely by BackgroundWorker.";
        }

        #region Windows Form Designer generated code

        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.setTextUnsafeBtn = new System.Windows.Forms.Button();
            this.setTextSafeBtn = new System.Windows.Forms.Button();
            this.setTextBackgroundWorkerBtn = new System.Windows.Forms.Button();
            this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
            this.SuspendLayout();
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(12, 12);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(240, 20);
            this.textBox1.TabIndex = 0;
            // 
            // setTextUnsafeBtn
            // 
            this.setTextUnsafeBtn.Location = new System.Drawing.Point(15, 55);
            this.setTextUnsafeBtn.Name = "setTextUnsafeBtn";
            this.setTextUnsafeBtn.TabIndex = 1;
            this.setTextUnsafeBtn.Text = "Unsafe Call";
            this.setTextUnsafeBtn.Click += new System.EventHandler(this.setTextUnsafeBtn_Click);
            // 
            // setTextSafeBtn
            // 
            this.setTextSafeBtn.Location = new System.Drawing.Point(96, 55);
            this.setTextSafeBtn.Name = "setTextSafeBtn";
            this.setTextSafeBtn.TabIndex = 2;
            this.setTextSafeBtn.Text = "Safe Call";
            this.setTextSafeBtn.Click += new System.EventHandler(this.setTextSafeBtn_Click);
            // 
            // setTextBackgroundWorkerBtn
            // 
            this.setTextBackgroundWorkerBtn.Location = new System.Drawing.Point(177, 55);
            this.setTextBackgroundWorkerBtn.Name = "setTextBackgroundWorkerBtn";
            this.setTextBackgroundWorkerBtn.TabIndex = 3;
            this.setTextBackgroundWorkerBtn.Text = "Safe BW Call";
            this.setTextBackgroundWorkerBtn.Click += new System.EventHandler(this.setTextBackgroundWorkerBtn_Click);
            // 
            // backgroundWorker1
            // 
            this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
            // 
            // Form1
            // 
            this.ClientSize = new System.Drawing.Size(268, 96);
            this.Controls.Add(this.setTextBackgroundWorkerBtn);
            this.Controls.Add(this.setTextSafeBtn);
            this.Controls.Add(this.setTextUnsafeBtn);
            this.Controls.Add(this.textBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion


        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }

    }
}

使用 BackgroundWorker 进行的线程安全调用

在应用程序中实现多线程的首选方式是使用 BackgroundWorker 组件。BackgroundWorker 组件使用事件驱动模型实现多线程。辅助线程运行 DoWork 事件处理程序,创建控件的线程运行 ProgressChanged 和 RunWorkerCompleted 事件处理程序。注意不要从 DoWork 事件处理程序调用您的任何控件。

下面的代码示例不异步执行任何工作,因此没有 DoWork 事件处理程序的实现。TextBox 控件的 Text 属性在 RunWorkerCompleted 事件处理程序中直接设置。

 

// This event handler starts the form's
// BackgroundWorker by calling RunWorkerAsync.
//
// The Text property of the TextBox control is set
// when the BackgroundWorker raises the RunWorkerCompleted
// event.
private void setTextBackgroundWorkerBtn_Click(
    object sender,
    EventArgs e)
{
    this.backgroundWorker1.RunWorkerAsync();
}

// This event handler sets the Text property of the TextBox
// control. It is called on the thread that created the
// TextBox control, so the call is thread-safe.
//
// BackgroundWorker is the preferred way to perform asynchronous
// operations.

private void backgroundWorker1_RunWorkerCompleted(
    object sender,
    RunWorkerCompletedEventArgs e)
{
    this.textBox1.Text =
        "This text was set safely by BackgroundWorker.";
}

 

Windows 窗体上的 ActiveX 控件

如果在窗体上使用 ActiveX 控件,则在调试器下运行时可能会收到线程间 InvalidOperationException。发生这种情况时,ActiveX 控件不支持多线程处理。有关使用 Windows 窗体的 ActiveX 控件的更多信息,请参见 Windows 窗体和非托管应用程序。

如果您使用的是 Visual Studio,则可以通过禁用 Visual Studio 宿主进程来防止此异常发生。

 

C#对 Windows 窗体控件进行线程安全调用 使用多线程提高 Windows 窗体应用程序的性能时,必须注意以线程安全方式调用控件。 访问 Windows 窗体控件本质上不是线程安全的。如果有两个或多个线程操作某一控件的状态,则可能会迫使该控件进入一种不一致的状态。还可能出现其他与线程相关的 bug,包括争用情况和死锁。确保以线程安全方式访问控件非常重要。 很多人遇到过工作线程workthread和UIthread 阅读详情

相关推荐

【Docker】Docker安装Hadoop分布式集群

hadoop目录安装在:/usr/local/hadoop-2.7.0/etc/hadoop。访问Hadoop102:9870,查看是否能够看到hdfs界面。访问hadoop103:8088,查看能够看到yarn界面。在yarn上可以看到执行情况。

weixin_46429290的博客 3460

多线程操作之窗体控件

ⅠWindows 窗体控件的线程安全性和InvokeRequired属性         Windows 窗体中的控件被绑定到特定的线程,不具备线程安全性。这就是说当我们企图从一个线程中操作在另一个线程中创建的控件时,可能会产生意想不到的错误。为此多线程环境下操作窗体控件时必须

Steven Lei的博客 1915

树莓派4B安装 ubuntu20.04 & VNC远程桌面 & 安装ROS noetic

树莓派4B安装ubuntu20.04 & VNC远程桌面1、安装ubuntu方式1:下载Imager文件。方式2:下载镜像文件。2、查询树莓派 IP 地址3、使用ssh远程登录树莓派4、更新源地址5、更新6、安装桌面环境7、允许root登陆8、登陆远程桌面9、设置中文 1、安装ubuntu 方式1:下载Imager文件。...

weixin_44415639的博客 2万+

MFC多线程编程注意事项

本文转自 http://www.blogjava.net/wangxinsh55/archive/2008/05/28/203464.html  1.      表现——错误示例关于启动线程时传输窗口对象(指针?句柄?)的问题:         在选择菜单中的开始线程后:     void   cmainframe::onmenu_start()     {           ...

理性的幻想 1347

Ubuntu22.04系统安装及配置

下载Ubuntu22.04系统镜像(下载地址:链接:https://caiyun.139.com/m/i?提取码:fLRJ),结合rufus和系统镜像制作USB启动盘,在物理机服务器上通过USB启动盘进行安装;或通过Esxi虚拟化平台创建虚拟机,然后在虚拟机中使用系统镜像进行安装。

cheagoun的博客 8万+

ns3-gym入门(二):linear-mesh例子详解

学习ns3-gym中关于IEEE 802.11网状网络中控制随机接入的例子linear-mesh

zoe2222226666的博客 1843

Win11系统线程异常未处理怎么办?Win11系统线程异常未处理解决方法

Win11系统线程异常未处理怎么办?相信有很多用户对于这一情况都是十分头疼的,大家不要着急,我们可以具体问题具体分析,使用不同的方法解决这个问题。 更多系统教程尽在小白系统重装官网   我们认为有必要先了解导致System Thread Exception not Handled问题的原因,然后才能尝试解决它,所以让我们开始吧。   启动时,Win11将自动检测并加载已安装在您机器上的所有基本驱动程序。驱动程序可能与您的Windows迭代不兼容,或者其中引入了错误。   因此将出现蓝屏死机 (B

qq_29508575的博客 1万+

ubuntu20 安装px4、mavros、QGroundControl

首先安装一下ant,否则没法运行,同时因20.04的缺少动态库libawt_xawt.so无法被Java8给调用,我的解决办法是去18.04把18.04的相同路径下的动态库libawt_xawt.so移动到20.04的/usr/lib/jvm/java-11-openjdk-amd64/lib/路径中。用rosdepc的时候,你得确保你用的是鱼香ROS的提供的ROS安装方法,否则是没有rosdepc的。make px4_sitl gazebo之前,可以安装一下gazebo的 模型。二、安装MAVROS。

qq_58060770的博客 3349

C#经验积累_03.浅谈在Windows窗口跨线程使用控件遇到“线程间操作无效: 从不是创建控件“textBox1”的线程访问它”异常的处理方法

03.浅谈在Windows窗口跨线程使用控件遇到“线程间操作无效: 从不是创建控件“textBox1”的线程访问它”异常的处理方法 在使用C#进行跨线程操作窗体控件时会遇到如下图中的异常: 异常起因: 在程序进程中windows框体处于一个独立的线程(下文称:主线程),当一个外部线程操作主线程中的控件或其他内容时,由于系统稳定性的限制不能直接进行跨线程操作的,便会出现以上异常信息。 可以通俗的如下理解: 有A,B两家公司,如果A公司需要使用B公司的专利B1,一般情况下是不能直接免费的使用B1的。如果A公司

qq_31862541的博客 5375

大模型量化方法总结

本文主要对大模型量化方法进行了总结,希望对学习大语言模型的同学们有所帮助。 文章目录 1. 前言 2. 模型精度 3. 量化方法 3.1 方法一 3.2 方法二 3.3 方法三

herosunly的博客 1万+

基于Simulink的单级式光伏并网系统MPPT控制仿真

本文基于Simulink平台,详细介绍了单级式光伏并网系统的MPPT控制仿真实现。主要内容包括:1)阐述MPPT作为光伏系统"智能大脑"的核心作用;2)解析单级式系统架构及扰动观察法(P&O)算法原理;3)以10kW户用系统为例,分步骤演示建模过程,包括光伏阵列搭建、P&O控制器实现(含MATLAB代码)、并网控制设计等;4)通过仿真验证系统在光照突变下的动态响应性能,MPPT效率达98.3%。文章还提出了变步长P&O等优化方向,为光伏系统仿真与控制提供实用指导。

xiaoheshang_123的博客 111

如何:对 Windows 窗体控件进行线程安全调用

如何:对 Windows 窗体控件进行线程安全调用 .NET Framework (current version) 其他版本   发布时间: 2016年5月 如果使用多线程处理来提高 Windows 窗体应用程序的性能,则你必须确保以线程安全的方式调用控件。 访问 Windows 窗体控件不是本身就线程安全的。 如果

老菜鸟 1014

STM实战开发(13):STM32开发:使用光敏电阻检测光照强度

光敏电阻(LDR)是一种电阻值受光照强度影响的半导体材料。当光照强度增大时,光敏电阻的电阻值降低;而当光照强度减小时,电阻值则增大。光敏电阻的电阻变化与入射光的强度之间并不是线性关系,而是呈对数型的变化。LDR通常由硫化镉(CdS)或其他半导体材料构成,材料对不同波长的光有不同的响应特性。一般而言,光照强度越强,光敏电阻的电阻值越低,反之则越高。本文介绍了如何使用STM32与光敏电阻(LDR)结合,进行光照强度检测的实现方法。通过配置STM32的ADC模块,读取光敏电阻的电压信号,并根据电压计算光照强度。

2201_76125393的博客 3018

Windows 窗体控件进行线程安全调用

Windows窗体控件进行线程安全调用 [caven 发表于 2006-4-8 16:49:32]

Chendy的专栏 1283

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Windows窗体控件进行线程安全调用

用Visual Studio 2005写了个很简单的程序,主要是在主窗体外创建了一个线程,让它专门刷新进度条。曾经在Visual Studio 2003里写过这个程序并且可以正常运行的,2005里却出现了异常。“线程间操作无效:不是从创建它的线程里访问。”哦,后来才发现这是2005的新特点。。对 Windows 窗体控件进行线程安全调用 使用多线程提高 Windows 窗体应用程序的性能时,必须注...

weixin_34228617的博客 142

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

如何对Windows窗体控件进行线程安全调用

使用多线程提高 Windows 窗体应用程序的性能时,必须注意以线程安全方式调用控件。 访问 Windows 窗体控件本质上不是线程安全的。如果有两个或多个线程操作某一控件的状态,则可能会迫使该控件进入一种不一致的状态。还可能出现其他与线程相关的 bug,包括争用情况和死锁。确保以线程安全方式访问控件非常重要。.NET Framework 有助于在以非线...

weixin_30642267的博客 85
上一篇: 关于MFC下检查和消除内存泄露的技巧
下一篇: How to call c++ exported method and classes in c#
RedRiver331
博客等级 码龄24年 1粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值