码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-09-23 17:41:24      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   ar   div   sp   art   

本文转载: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。主要出现问题代码如下:

bubuko.com,布布扣
   protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            txtRFID_Click(null, null);

        }
View Code

 

   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 = -1;
                string strTid = "";
                iRet = WriteCardHelper.Instance.ReadTID(ref strTid); //读取耗时的代码;注意:耗时的代码不能放在 this.BeginInvoke(new MethodInvoker(() => 耗时代码 })); //中执行;否则没有产生异步的效果。BeginInvoke中只能放置操作控件的代码。

                if (this.IsHandleCreated)
                    this.BeginInvoke(new MethodInvoker(() =>
                    {
                        this.errorProvider.SetError(this.txtRFID, "");
                        if (0 == 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)判断就可以了。

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

标签:style   blog   http   color   os   ar   div   sp   art   

原文地址:http://www.cnblogs.com/zfanlong1314/p/3988662.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!