您的位置:首页 > 理论基础 > 计算机网络

delegate 与 多线程(摘自网络)

2007-03-25 16:45 337 查看

delegate 与 多线程

http://www.putfly.com/show.aspx?id=252&cid=11
很多时候写windows程序都需要结合多线程,在.net中用如下得代码来创建并启动一个新的线程。

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();

这里只是我的一些理解,如果有什么错误或者不当的地方,欢迎指出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: