delegate 与 多线程(摘自网络)
2007-03-25 16:45
337 查看
delegate 与 多线程
http://www.putfly.com/show.aspx?id=252&cid=11 |
public void ThreadProc();
Thread thread = new Thread( new ThreadStart( ThreadProc ) );
thread.IsBackground = true;
thread.Start();
但是很多时候,在新的线程中,我们需要与UI进行交互,在.net中不允许我们直接这样做。可以参考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)
OutDelegate outdelegate = new OutDelegate( OutText );
public delegate void OutDelegate(string text);
public void OutText(string text)
public void ThreadProc()
public class ProcClass
ProcClass threadProc = new ProcClass("use thread class");
Thread thread = new Thread( new ThreadStart( threadProc.ThreadProc ) );
thread.IsBackground = true;
thread.Start();
就是这样,需要建立一个中间类来传递线程所需的参数。
那么如果我的线程又需要参数,又需要和UI进行交互的时候该怎么办呢?可以修改一下代码:
public class ProcClass
ProcClass threadProc = new ProcClass("use thread class", new OutDelegate(OutText));
Thread thread = new Thread( new ThreadStart( threadProc.ThreadProc ) );
thread.IsBackground = true;
thread.Start();
这里只是我的一些理解,如果有什么错误或者不当的地方,欢迎指出。
相关文章推荐
- java并发多线程(摘自网络)
- Windows Forms 实现安全的多线程详解(附带程序代码示例) (摘自网络)
- C#中的多线程(摘自网络)
- 使用WIF实现单点登录Part III —— 正式实战 -摘自网络
- java socket 多线程网络传输多个文件
- 第03天多线程网络:(10):NSCache简单介绍
- Android开发 多线程网络请求
- iOS开发网络请求——大文件的多线程断点下载
- Android 多线程下载网络文件
- Android实现网络多线程文件下载
- 网游服务器网络层IO多线程
- ios多线程操作(十二)—— 自定义NSOperation实现网络下载后回调
- 新建虚拟目录使用UNC共享文件夹(即:虚拟目录使用UNC共享文件夹)的方法 -摘自网络
- javaSE(24)(多线程、网络编程、反射)
- 黄健翔,请你像个男人一样去向全国的球迷道歉!(摘自网络)
- linux网络编程之多线程多进程服务器与进程线程池
- 第01天多线程网络:(08):线程的状态(了解)
- MongoDB索引相关文章-摘自网络
- 第01天多线程网络:(15):同步和异步函数的区别和总结
- 摘自网络--"浅析UpdatePanel的partial render原理"