欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中跨线程访问控件问题解决方案分享

程序员文章站 2024-02-16 22:57:16
net 原则上禁止跨线程访问控件,因为这样可能造成错误的发生,推荐的解决方法是采用代理,用代理方法来间接操作不是同一线程创建的控件。 第二种方法是禁止编译器对跨线程访问作...

net 原则上禁止跨线程访问控件,因为这样可能造成错误的发生,推荐的解决方法是采用代理,用代理方法来间接操作不是同一线程创建的控件。

第二种方法是禁止编译器对跨线程访问作检查,可以实现访问,但是出不出错不敢保证control.checkforillegalcrossthreadcalls = false;

最近我在做一个项目,遇到了跨线程要去访问页面控件.但是总是提示出错,不能在其它线程中修改创建控件的线程的控件的值,后来采用了匿名代理,结果很轻松地解决了.解决过程如下:
首先在窗体上,创建一个listbox,lable.

复制代码 代码如下:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.text;
using system.windows.forms;
using system.threading;

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

        private void form1_load(object sender, eventargs e)
        { 
            thread newthread = new thread(new threadstart(backgroundprocess));
            newthread.start();        

        }

        /// <summary>
        /// 定义一个代理
        /// </summary>
        private delegate void crossthreadoperationcontrol();

        private void backgroundprocess()
        {
            // 将代理实例化为一个匿名代理
            crossthreadoperationcontrol crossdelete = delegate()         
            {           
                int i = 1;
                while (i<5)
                {
                   // 向列表框增加一个项目
                    listbox1.items.add("item " + i.tostring());                  
                    i++;
                }
                label1.text = "我在新线程里访问这个lable!";
                listbox1.items.add(label1.text);
            }  ;
            listbox1.invoke(crossdelete);          
        }      

    }
}

希望这个小技巧能够对你的的学习和工作有所帮助.若有更好的办法来解决跨线程访问控件的问题,不防也拿出来大家分享一下.

c#跨线程访问控件运行时错误,使用methodinvoker即可解决:

原代码:

复制代码 代码如下:

private void btnok_click(object sender, eventargs e)
        {
            tslinfo.text = "请稍候...";


            thread td = new thread(new threadstart(run));
            td.start();
        }


        /// <summary>
        /// 线程方法
        /// </summary>
        private void run()
        {
            this.tslinfo.text = "就绪";
        }


修改后:
复制代码 代码如下:

private void btnok_click(object sender, eventargs e)
        {
            tslinfo.text = "请稍候...";


            thread td = new thread(new threadstart(threadrun));
            td.start();
        }


        /// <summary>
        /// 原线程方法
        /// </summary>
        private void run()
        {
            this.tslinfo.text = "就绪";
        }

        /// <summary>
        /// 线程方法
        /// </summary>
        private void threadrun()
        {
            methodinvoker in = new methodinvoker(run);
            this.begininvoke(in);
        }


我们在做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=new flushclient(threadfunction);

             flushclient.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)
        {
            thread thread = new thread(crossthreadflush);
             flushclient=new flushclient(threadfunction);

             flushclient.begininvoke(null,null);
        }

         private void threadfunction()
        {

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

        }
    }