C# 直接在子线程中对窗体上的控件操作是会出现异常

https://www.bbsmax.com/A/MAzA8klpd9/

 

Form1里

       private delegate void DispMSGDelegate(int index, string MSG);


        public void DispMsg(int iIndex, string strMsg)
        {
            if (this.richTextBox1.InvokeRequired == false)                      //如果调用该函数的线程和控件lstMain位于同一个线程内
            {
                //直接将内容添加到窗体的控件上
                if (0 == iIndex) {
                        this.showResultButtons(true);
                        this.setTestMenus(false);
                }
            }
            else                                                        //如果调用该函数的线程和控件lstMain不在同一个线程
            {
                //通过使用Invoke的方法,让子线程告诉窗体线程来完成相应的控件操作
                DispMSGDelegate DMSGD = new DispMSGDelegate(DispMsg);

                //使用控件lstMain的Invoke方法执行DMSGD代理(其类型是DispMSGDelegate)
                this.richTextBox1.Invoke(DMSGD, iIndex, strMsg);

            }
        }

 

其他线程或者回调里调用

                    if (0 == rtn)
                    {
                        if (mtestType == EMT_TEST_TYPE.CAMERA_ADUIO_START ||
                           mtestType == EMT_TEST_TYPE.CAMERA_ADUIO_STOP ||
                           mtestType == EMT_TEST_TYPE.CAMERA_PLAY ||
                           mtestType == EMT_TEST_TYPE.CAMERA_MOVE_HORIZONTAL ||
                           mtestType == EMT_TEST_TYPE.CAMERA_MOVE_UPDOWN ||
                           mtestType == EMT_TEST_TYPE.CAMERA_MOVE_STOP ||
                           mtestType == EMT_TEST_TYPE.CAMERA_KEY ||
                           mtestType == EMT_TEST_TYPE.CAMERA_INFRAREDLED ||
                           mtestType == EMT_TEST_TYPE.CAMERA_IRCUT)
                        {
                            //Program.f1.addLog("setShowRB1:");
                            Program.f1.DispMsg(0, "");
                        }
                    }

 

posted @ 2023-04-01 17:12  cnchengv  阅读(29)  评论(0编辑  收藏  举报