ThreadStart()笔记

来源:互联网 发布:centos iscsi 编辑:程序博客网 时间:2024/05/19 17:04

语法

C#[ComVisibleAttribute(true)]public delegate void ThreadStart()

用法说明

当创建托管线程时,在线程上执行的方法由传递给Thread构造函数的ThreadStart委托或ParameterizedThreadStart委托表示。线程调用Thread.Start()方法后,线程才会正式开始执行。执行从由ThreadStart或ParameterizedThreadStart代表表示的方法的第一行开始。

注意

创建线程时,Visual Basic和C#用户可以省略ThreadStart或ParameterizedThreadStart委托构造函数。在Visual Basic中,在将方法传递给Thread构造函数时,使用AddressOf运算符; 例如,Dim t As New Thread(AddressOf ThreadProc)。在C#中,只需指定线程程序的名称即可。编译器会选择正确的委托构造函数。

正确示例

using System;using System.Threading;class Test{    static void Main()     {        // 要使用静态线程过程启动线程,请在创建ThreadStart()时使用类名和方法名        //Beginning in version 2.0 of the .NET Framework,        // it is not necessary to create a delegate explicitly.         // Specify the name of the method in the Thread constructor,         // and the compiler selects the correct delegate. For example:        //        // Thread newThread = new Thread(Work.DoWork);        //        ThreadStart threadDelegate = new ThreadStart(Work.DoWork);        Thread newThread = new Thread(threadDelegate);        newThread.Start();        // 要使用静态线程过程启动线程,请在创建ThreadStart delegate 时使用具体的类实例名和函数名        Work w = new Work();        w.Data = 42;        threadDelegate = new ThreadStart(w.DoMoreWork);        newThread = new Thread(threadDelegate);        newThread.Start();    }}class Work {    public static void DoWork()     {        Console.WriteLine("Static thread procedure.");     }    public int Data;    public void DoMoreWork()     {        Console.WriteLine("Instance thread procedure. Data={0}", Data);     }}/* This code example produces the following output (the order    of the lines might vary):Static thread procedure.Instance thread procedure. Data=42 */
原创粉丝点击