C#:ThreadStart 委托

大家好,今天还是继续介绍Thread相关的内容。

定义

命名空间:

System.Threading

程序集:

mscorlib.dll

表示在 Thread 上执行的方法。

C#复制

[System.Runtime.InteropServices.ComVisible(true)]
public delegate void ThreadStart();

属性

ComVisibleAttribute

示例

下面的代码示例演示用于通过实例方法和 ThreadStart 静态方法创建和使用委托的语法。

有关演示如何创建委托的另一个 ThreadStart 简单示例,请参阅 Thread.Start() 方法重载。 有关线程创建的详细信息,请参阅 在开始时间创建线程和传递数据

C#复制

using System;
using System.Threading;

class Test
{
    static void Main() 
    {
        // To start a thread using a static thread procedure, use the
        // class name and method name when you create the ThreadStart
        // delegate. 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();

        // To start a thread using an instance method for the thread 
        // procedure, use the instance variable and method name when 
        // you create the ThreadStart delegate. Beginning in version
        // 2.0 of the .NET Framework, the explicit delegate is not
        // required.
        //
        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
 */

注解

创建托管线程时,在线程上执行的方法由传递给Thread构造函数的ThreadStart委托或ParameterizedThreadStart委托表示。 在调用 方法之前, Thread.Start 线程不会开始执行。 执行从 或 ParameterizedThreadStart 委托表示ThreadStart的方法的第一行开始。

 备注

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

对于 C++,从 .NET Framework 2.0 开始,为静态方法创建ThreadStart委托只需要一个参数:回调方法的地址,由类名限定。 在早期版本中,为静态方法创建委托时需要两个参数:零 (null) 和方法地址。 对于实例方法,所有版本都需要两个参数:实例变量和方法地址。

扩展方法

展开表

GetMethodInfo(Delegate)

获取指示指定委托表示的方法的对象。

今天要介绍的就是这么多,我们下篇文章再见。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵桑さん

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值