📜  C#| Thread(ParameterizedThreadStart)构造函数

📅  最后修改于: 2021-05-30 01:28:12             🧑  作者: Mango

Thread(ParameterizedThreadStart)构造函数用于初始化Thread类的新实例。它定义了一个委托,该委托允许对象在线程启动时传递给线程。如果此构造函数的参数为null,则此构造函数将提供ArgumentNullException。

Synatx:

public Thread(ParameterizedThreadStart start);

在这里, start是一个委托,代表当该线程开始执行时要调用的方法。

下面的程序说明了Thread(ParameterizedThreadStart)构造函数的用法:

范例1:

// C# program to illustrate the
// use of Thread(ParameterizedThreadStart)
// constructor with non-static method
using System;
using System.Threading;
  
public class MYTHREAD {
  
    // Non-static method
    public void Job()
    {
        for (int z = 0; z < 3; z++) {
  
            Console.WriteLine("My thread is "+
                          "in progress...!!");
        }
    }
}
  
// Driver Class
public class GFG {
  
    // Main Method
    public static void Main()
    {
        // Creating object of MYTHREAD class
        MYTHREAD obj = new MYTHREAD();
  
        // Creating a thread which
        // calls a parameterized instance method
        Thread thr = new Thread(obj.Job);
        thr.Start();
    }
}

输出:

My thread is in progress...!!
My thread is in progress...!!
My thread is in progress...!!

范例2:

// C# program to illustrate the use of
// Thread(ParameterizedThreadStart)
// constructor with static method
using System;
using System.Threading;
  
// Driver Class
public class GFG {
  
    // Main Method
    public static void Main()
    {
        // Creating a thread which calls 
        // a parameterized static-method
        Thread thr = new Thread(Job);
        thr.Start();
    }
  
    // Static method
    public static void Job()
    {
        Console.WriteLine("My thread is"+
                    " in progress...!!");
  
        for (int z = 0; z < 3; z++) {
            Console.WriteLine(z);
        }
    }
}

输出:

My thread is in progress...!!
0
1
2

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.thread.-ctor?view=netframework-4.7.2#System_Threading_Thread__ctor_System_Threading_ParameterizedThreadStart_