线程间操作无效,从不是创建控件的线程访问控件的解决方案

来源:互联网 发布:常见的网络诈骗手段 编辑:程序博客网 时间:2024/06/06 13:20

    其实很久以前就碰到过这个问题了,只是一直没有时间对其进行整理。这次在开发过程中又碰上了,所以感觉有必要把它整理一下。

 

    网上一种非常简单的方法,在初始化的地方加上“CheckForIllegalCrossThreadCalls = false”这句代码便可,如果幸运的话,可能不会报错。MSDN解释如下:

 

“如果试图访问控件的方法或属性之一的线程不是创建该控件的线程,则通常会导致不可预知的结果。通常,无效的线程活动是对访问控件的 Handle 属性的错误线程的调用。将 CheckForIllegalCrossThreadCalls 设置为 true 可以更容易地查找并诊断此线程活动。”

 

    显然将其设置成false只是简略了这种错误而已。如果你在程序中用到第三方控件的话,系统还是会报一些奇怪的错误,例如我这次就报了个集合已修改可能无法执行枚举操作”的错误。所以建议在开发不过程中如果使用到第三方控件的话最好不要使用以上方法。应该使用异步操作,步骤如下:

 

  1.声明委托

         // 解决跨线程调用

        private delegate void SetGatherButtonImageHandle(bool status);

        private SetGatherButtonImageHandle setGatherButtonImageHandle;

 

 

  2.创建委托

     setGatherButtonImageHandle = new SetGatherButtonImageHandle(SetGatherButtonImage);

 

  3.提取处理部分

 

        // 解决跨线程调用

        private void SetGatherButtonImage(bool status)

        {

            if (false == status)

            {

                picStartGather.Enabled = false;

                picStartGather.Image = SingleChannlGatherCtrl.Properties.Resources.bt_start_gather3;

 

                picStopGather.Enabled = true;

                picStopGather.Image = SingleChannlGatherCtrl.Properties.Resources.bt_stop_gather;

            }

            else

            {

                picStartGather.Enabled = true;

                picStartGather.Image = SingleChannlGatherCtrl.Properties.Resources.bt_start_gather;

 

                picStopGather.Enabled = false;

                picStopGather.Image = SingleChannlGatherCtrl.Properties.Resources.bt_stop_gather3;

            }

        }

 

 

  4.在出错的地方使用如下方法调用

 

                    if (true == picStartGather.InvokeRequired)

                    {

                        this.Invoke(setGatherButtonImageHandle, false);

                    }

                    else

                    {

                        SetGatherButtonImage(false);

                    }

 

原创粉丝点击