线程间操作无效: 从不是创建控件“textBox1”的线程访问它。

问题产生和现象:

垮线程调用控件属性,现象如下:

解决方法:

方法1

 
  
Control.CheckForIllegalCrossThreadCalls = false ;

 

方法2

 
  
private void button1_Click( object sender, EventArgs e)
{
Thread.CurrentThread.Name
= " Form Thread " ;
Thread td
= new Thread( new ThreadStart(SetControlText));
td.Name
= " Customer Thread " ;
td.Start();
}
private void SetControlText()
{
if ( this .InvokeRequired)
{
this .Invoke( new Action(SetControlText));
}
else
{
this .textBox1.Text = DateTime.Now.ToString();
}
}

 

通用起见,可以考虑这样做:

 
  
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
Thread.CurrentThread.Name
= " Form Thread " ;
Thread td
= new Thread( new ThreadStart(SetControlText));
td.Name
= " Customer Thread " ;
td.Start();
}
private void SetControlText()
{
this .InvokeIfNeeded( delegate ( string str) { this .textBox1.Text = str; }, DateTime.Now.ToString( " yyMMdd " ));
// or
// this.InvokeIfNeeded((str)=> this.textBox1.Text = str,DateTime.Now.ToString("yyMMdd"));
}
}
public static class ControlExtensions
{
public static void InvokeIfNeeded < T > ( this Control ctl, Action < T > act, T args)
{
if (ctl.InvokeRequired)
{
ctl.Invoke(act, args);
}
else
{
act(args);
}
}
}

 

 

备注:

Control.InvokeRequired Property

Usage

Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on.

Property Value
true if the control's Handle was created on a different thread than the calling thread (indicating that you must make calls to the control through an invoke method); otherwise, false.

转载于:https://www.cnblogs.com/cnbwang/archive/2011/01/01/1923678.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值