C#中线程的委托
很多时候写windows程序都需要结合多线程,在c#中用如下得代码来创建并启动一个新的线程。
thread thread = new thread(new threadstart(threadproc));//实例化一个线程 thread.isbackground = true;//将线程改为后台线程 thread.start();//开启线程
但是很多时候,在新的线程中,我们需要与ui(windows窗体设计器用户界面)进行交互,在c#中不允许直接这样做。可以参考msdn中的描述。
“windows 窗体”使用单线程单元 (sta) 模型,因为“windows 窗体”基于本机win32窗口,而win32窗口从本质上而言是单元线程。sta模型意味着可以在任何线程上创建窗口,但窗口一旦创建后就不能切换线程,并且对它的所有函数调用都必须在其创建线程上发生。除了windows窗体之外,.net framework 中的类使用*线程模型。
sta模型要求需从控件的非创建线程调用的控件上的任何方法必须被封送到(在其上执行)该控件的创建线程。基类control为此目的提供了若干方法(invoke、begininvoke 和 endinvoke)。invoke生成同步方法调用;begininvoke生成异步方法调用。
windows窗体中的控件被绑定到特定的线程,不具备线程安全性。因此,如果从另一个线程调用控件的方法,那么必须使用控件的一个invoke方法来将调用封送到适当的线程。
正如所看到的,必须调用invoke方法,而begininvoke可以认为是invoke的异步版本。调用方法如下:
public delegate void outdelegate(string text); public void outtext(string text) { txt.appendtext(text); txt.appendtext( "\t\n" ); } outdelegate outdelegate = new outdelegate( outtext ); this.begininvoke(outdelegate, new object[]{text});
如果需要在另外一个线程里面对ui进行操作,需要一个类似outtext的函数,还需要一个该函数的委托delegate,当然,这里展示的是自定义的。
该属性可用于确定是否必须调用 invoke 方法,当不知道什么线程拥有控件时这很有用。
也就是说通过判断invokerequired可以知道是否需要用委托来调用当前控件的一些方法,如此可以把outtext函数修改一下:
public delegate void outdelegate(string text); public void outtext(string text) { if( txt.invokerequired ) { outdelegate outdelegate = new outdelegate( outtext ); this.begininvoke(outdelegate, new object[]{text}); return; } txt.appendtext(text); txt.appendtext( "\t\n" ); }
注意,这里的函数没有返回,如果有返回,需要调用invoke或者endinvoke来获得返回的结果,不要因为包装而丢失了返回值。如果调用没有完成,invoke和endinvoke都将会引起阻塞。
现在如果我有一个线程函数如下:
public void threadproc() { for(int i = 0; i < 5; i++) { outtext( i.tostring() ); thread.sleep(1000); } }
如果循环的次数很大,或者漏了thread.sleep(1000);,那么你的ui肯定会停止响应,想知道原因吗?看看begininvoke前面的对象,没错,就是this,也就是主线程,当你的主线程不停的调用outtext的时候,ui当然会停止响应。
与以前vc中创建一个新的线程需要调用afxbeginthread函数,该函数中第一个参数就是线程函数的地址,而第二个参数是一个类型为lpvoid的指针类型,这个参数将传递给线程函数。现在我们没有办法再使用这种方法来传递参数了。我们需要将传递给线程的参数和线程函数包装成一个单独的类,然后在这个类的构造函数中初始化该线程所需的参数,然后再将该实例的线程函数传递给thread类的构造函数。代码大致如下:
public class procclass { private string procparameter = ""; public procclass(string parameter) { procparameter = parameter; } public void threadproc() { } } procclass threadproc = new procclass("use thread class"); thread thread = new thread( new threadstart( threadproc.threadproc ) ); thread.isbackground = true; thread.start();
就是这样,需要建立一个中间类来传递线程所需的参数。
那么如果我的线程又需要参数,又需要和ui进行交互的时候该怎么办呢?可以修改一下代码:
public class procclass { private string procparameter = ""; private form1.outdelegate delg = null; public procclass(string parameter, form1.outdelegate delg) { procparameter = parameter; this.delg = delg; } public void threadproc() { delg.begininvoke("use procclass.threadproc()", null, null); } } procclass threadproc = new procclass("use thread class", new outdelegate(outtext)); thread thread = new thread( new threadstart( threadproc.threadproc ) ); thread.isbackground = true; thread.start();