在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。

本文转载:http://blog.csdn.net/playing9c/article/details/7471918

http://blog.csdn.net/beelinkerlidejun/article/details/4772491

http://www.cnblogs.com/fish124423/archive/2012/10/16/2726543.html

C#窗体的多线程一直是个难题,总是要出现奇奇怪怪的错误。今天开发alexSEO软件时,出现了在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。主要出现问题代码如下:

   protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
txtRFID_Click(null, null); }
   private void txtRFID_Click(object sender, EventArgs e)
{
Thread thread = new Thread(() =>
{
if (this.IsHandleCreated)
this.BeginInvoke(new MethodInvoker(() =>
{
this.txtRFID.Enabled = false;
})); int iRet = -;
string strTid = "";
iRet = WriteCardHelper.Instance.ReadTID(ref strTid); //读取耗时的代码;
//注意:耗时的代码不能放在 this.BeginInvoke(new MethodInvoker(() => 耗时代码 })); //中执行;否则没有产生异步的效果。
//BeginInvoke中只能放置操作控件的代码。BeginInvoke将子线程线程通过委托抛向UI主线程 。 if (this.IsHandleCreated)
this.BeginInvoke(new MethodInvoker(() =>
{
this.errorProvider.SetError(this.txtRFID, "");
if ( == iRet)
{
WriteCardHelper.Instance.SetAlarm();
this.txtRFID.Text = strTid;
this.txtRFID.BackColor = Color.White;
this.errorProvider.SetError(this.txtRFID, "");
}
else
{
this.txtRFID.Text = "";
this.txtRFID.BackColor = Color.Pink; }
this.txtGasBottleNo.Focus();
this.txtRFID.Enabled = true;
}));
});
thread.IsBackground = true;
thread.Start();
}

客户端:(实现异步打开窗体,该窗体加载的时候会读取设备的数据,但会很耗时,为了防止窗体加载时候由于耗时的代码,导致不能及时的显示出来)

 frmGasBottlesInstall frmInstall = new frmGasBottlesInstall(gasBottlesID);
frmInstall.ShowDialog(); //异步打开窗口。

当调试运行中突然关闭软件时,labb.Invoke(labchange);语句就出先了“在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。”错误。想了一通出现这种情况应该有两种可能。第一种应该是界面还来不及响应Invoke,第二种是界面线程已经结束,所以响应不了。最后解决办法是在labb.Invoke(labchange);前加一个if(labb.IsHandleCreated)判断就可以了。

上一篇:Delphi 实现不规则窗体


下一篇:浏览器d判断