当前位置: 移动技术网 > IT编程>开发语言>c# > c#中多线程访问winform控件的若干问题小结

c#中多线程访问winform控件的若干问题小结

2019年07月18日  | 移动技术网IT编程  | 我要评论

我们在做winform应用的时候,大部分情况下都会碰到使用多线程控制界面上控件信息的问题。然而我们并不能用传统方法来解决这个问题,下面我将详细的介绍。

首先来看传统方法:

复制代码 代码如下:

public partial class form1 : form
     {
        public form1()
        {
            initializecomponent();
        }

        private void form1_load(object sender, eventargs e)
        {
            thread thread = new thread(threadfuntion);
            thread.isbackground = true;
            thread.start();
        }
        private void threadfuntion()
        {
            while (true)
            {
                this.textbox1.text = datetime.now.tostring();
                thread.sleep(1000);
            }
        }
    }

运行这段代码,我们会看到系统抛出一个异常:cross-thread operation not valid:control 'textbox1' accessed from  a thread other than the thread it was created on . 这是因为.net 2.0以后加强了安全机制,不允许在winform中直接跨线程访问控件的属性。那么怎么解决这个问题呢,下面提供几种方案。

      第一种方案,我们在form1_load()方法中加一句代码:

复制代码 代码如下:

private void form1_load(object sender, eventargs e)
      {
            control.checkforillegalcrossthreadcalls = false;
            thread thread = new thread(threadfuntion);
            thread.isbackground = true;
            thread.start();
      }

加入这句代码以后发现程序可以正常运行了。这句代码就是说在这个类中我们不检查跨线程的调用是否合法(如果没有 加这句话运行也没有异常,那么说明系统以及默认的采用了不检查的方式)。然而,这种方法不可取。我们查看checkforillegalcrossthreadcalls 这个属性的定义,就会发现它是一个static的,也就是说无论我们在项目的什么地方修改了这个值,他就会在全局起作用。而且像这种跨线程访问是否存在异常,我们通常都会去检查。如果项目中其他人修改了这个属性,那么我们的方案就失败了,我们要采取另外的方案。

下面来看第二种方案,就是使用delegate和invoke来从其他线程中控制控件信息。网上有很多人写了这种控制方式,然而我看了很多这种帖子,表明上看来是没有什么问题的,但是实际上并没有解决这个问题,首先来看网络上的那种不完善的方式:

复制代码 代码如下:

public partial class form1 : form
    {
        private delegate void flushclient();//代理
        public form1()
        {

            initializecomponent();
        }

        private void form1_load(object sender, eventargs e)

        {
            thread thread = new thread(crossthreadflush);
            thread.isbackground=true;
            thread.start();
        }


        private void crossthreadflush()
        {
            //将代理绑定到方法
            flushclient fc = new flushclient(threadfuntion);
            this.begininvoke(fc);//调用代理
        }

        private void threadfuntion()
        {
            while (true)
            {
                this.textbox1.text = datetime.now.tostring();
                thread.sleep(1000);
            }
        }
    }

使用这种方式我们可以看到跨线程访问的异常没有了。但是新问题出现了,界面没有响应了。为什么会出现这个问题, 我们只是让新开的线程无限循环刷新,理论上应该不会对主线程产生影响的。其实不然,这种方式其实相当于把这个新开的线程“注入”到了主控制线程中,它取得了主线程的控制。只要这个线程不返回,那么主线程将永远都无法响应。就算新开的线程中不使用无限循环,使可以返回了。这种方式的使用多线程也失去了它本来的意义。

现在来让我们看看推荐的解决方案:

复制代码 代码如下:

public partial class form1 : form
    {
        private delegate void flushclient();//代理
        public form1()
        {
            initializecomponent();
        }

        private void form1_load(object sender, eventargs e)
        {
            thread thread = new thread(crossthreadflush);
            thread.isbackground = true;
            thread.start();
        }


        private void crossthreadflush()
        {
            while (true)
            {
                //将sleep和无限循环放在等待异步的外面
                thread.sleep(1000);
                threadfunction();
            }
        }

        private void threadfunction()
        {
            if (this.textbox1.invokerequired)//等待异步
            {
                flushclient fc = new flushclient(threadfunction);
                this.invoke(fc);//通过代理调用刷新方法
            }
            else
            {
                this.textbox1.text = datetime.now.tostring();
            }
        }
    }

运行上述代码,我们可以看到问题已经被解决了,通过等待异步,我们就不会总是持有主线程的控制,这样就可以再不发生跨线程调用异常的情况下完成多线程对winform多线程控件的控制了。

对于深山老林提出的问题,我最近找到了更优的解决方案,利用了delegate的异步调用,大家可以看看:

复制代码 代码如下:

public partial class form1 : form
    {
        private delegate void flushclient();//代理
        public form1()
        {
            initializecomponent();
        }

        private void form1_load(object sender, eventargs e)
        {
            thread thread = new thread(crossthreadflush);
            thread.isbackground = true;
            thread.start();
        }


        private void crossthreadflush()
        {
             flushclient fc=new flushclient(threadfunction);
             fc.begininvoke(null,null);
        }

        private void threadfunction()
        {
              while (true)
            {
                this.textbox1.text = datetime.now.tostring();
                thread.sleep(1000);
            }
        }
    }

这种方法也可以直接简化为(因为delegate的异步就是开了一个异步线程):

复制代码 代码如下:

public partial class form1 : form
    {
        private delegate void flushclient();//代理
        public form1()
        {
            initializecomponent();
        }

        private void form1_load(object sender, eventargs e)
        {
             flushclient fc=new flushclient(threadfunction);
             fc.begininvoke(null,null);
        }

         private void threadfunction()
        {
              while (true)
            {

                this.textbox1.text = datetime.now.tostring();
                thread.sleep(1000);
            }
        }
    }

贫僧用飘柔反馈

while (true)和thread.sleep(1000);不要放在invoke里面去控制就行了

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网