C#多线程窗体控件安全访问

本文介绍在C#中如何实现子线程安全地访问窗体控件,通过使用Invoke方法确保线程间的操作不会引发异常。演示了一个具体的示例程序,展示了如何更新窗体控件上的文本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C#多线程窗体控件安全访问

 


 

C# 2.0 为了线程安全,不充许子线程直接访问窗体中的控件
如果在子线程中直接访问说窗体控件,编译器会提示,控件不是
由该线程创建的.


那么在子线程中如何访问窗体中的控件呢?
在窗体的构造函数中加入这一句
Control.CheckForIllegalCrossThreadCalls = false;
子线程就可以直接访问窗体中的控件了,不过这样线程是非安全的.
而默认Control.CheckForIllegalCrossThreadCalls=true;(捕获线程错误调用)
这时可以用Invoke

如下:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Project2
{
   

    
public partial class Form1 : Form
    {
        
private BackgroundWorker backgroundWorker1;

        
protected delegate void UpdateControlText(string strText);//定义一个委托
        
//定义更新控件的方法
        protected void updateControlText(string strText)
        {
           
this.label1.Text  = strText ;
            
return;
        }


        
public Form1()
        {
            
//Control.CheckForIllegalCrossThreadCalls = false;

            InitializeComponent();
        }


        
private void button1_Click(object sender, EventArgs e)
        {
            Thread ff 
= new Thread( new ThreadStart ( x2));
            ff.Start();
        }

        
private void x1()//线程安全的访问窗体控件
        {
            
for (int i = 0; i < 1000; i++)
            {
                
long xx = Convert.ToInt32(this.label1.Text);
                
if (this.InvokeRequired)
                {
                    UpdateControlText update 
= new UpdateControlText(updateControlText);//用更新控件的方法updateControlText实例化一个委托update
                    this.Invoke(update, Convert.ToString(++xx));//调用窗体Invoke方法

                }
                
else
                {
                    
this.label1.Text = Convert.ToString(++xx);
                }
            }
        }

     }

 }
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值