zoukankan      html  css  js  c++  java
  • 在创建窗口句柄之前,不能在控件上调用 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);
    
            }
    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中只能放置操作控件的代码。BeginInvoke将子线程线程通过委托抛向UI主线程 。
    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)判断就可以了。

  • 相关阅读:
    JavaWeb网站技术架构
    fullcalendar插件日程管理
    PuTTY/终端使用复制、粘贴
    JAVA PERSISTENCE API (JPA)
    mysql查询当天所有数据sql语句
    Sign http
    js在新页面中返回到上一页浏览的历史位置
    Android使用Activity用作弹出式对话框
    android listview局部刷新和模拟应用下载
    如何获取drawable目录下的图片绝对路径
  • 原文地址:https://www.cnblogs.com/51net/p/3988662.html
Copyright © 2011-2022 走看看