ThreadStart()笔记

语法

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
 */
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值