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