線程操作主要用到Thread類,他是定義在System.Threading.dll下。使用時需要添加這一個引用。該類提供給我們四個重載的構造函
構造函數定義:
無參數委托
[SecuritySafeCritical] public Thread(ThreadStart start); [SecuritySafeCritical] public Thread(ThreadStart start, int maxStackSize);
有一個參數object委托
[SecuritySafeCritical] public Thread(ParameterizedThreadStart start); [SecuritySafeCritical] public Thread(ParameterizedThreadStart start, int maxStackSize); // maxStackSize: // 線程要使用的最大堆棧大小(以字節為單位);如果為 0 則使用可執行文件的文件頭中指定的默認最大堆棧大小。重要地,對於部分受信任的代碼,如果 maxStackSize // 大於默認堆棧大小,則將其忽略。不引發異常。
一、創建沒有參數傳入線程
//創建沒有參數的線程 Thread thread = new Thread(new ThreadStart(ThreadMethod)); //或者 //Thread thread = new Thread(ThreadMethod); thread.Start(); Console.WriteLine("代碼執行完成");
//線程方法定義 public static void ThreadMethod() { Console.WriteLine("當前線程ID:{0},當前線程名稱:{1}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name); while (true) { Console.WriteLine(DateTime.Now); Thread.Sleep(1000); } }
二、創建一個參數傳入object類型的線程
public static void Init() { //創建一個參數的線程 //ParameterizedThreadStart 指定傳入的類型是object for (int i = 0; i < 3; i++) { Thread thread = new Thread(new ParameterizedThreadStart(ThreadMethod)); object obj = i * 10; thread.Start(obj); } } //定義線程方法 public static void ThreadMethod(object number) { int i = (int)number; while (true) { i++; Console.WriteLine("當前線程ID:{0},number={1}", Thread.CurrentThread.ManagedThreadId, i); Thread.Sleep(2000); } }
三、創建使用對象實例方法,創建多個參數傳入情況的線程
public static void Init() { //創建多個傳入參數的線程 for (int i = 1; i < 4; i++) { Calculator cal = new Calculator(i, i * 100); Thread thread = new Thread(new ThreadStart(cal.Add)); thread.Start(); } }
public class Calculator { public int X { get; set; } public int Y { get; set; } public Calculator(int x, int y) { this.X = x; this.Y = y; } //定義線程執行方法 public void Add() { int i = 0; while (i < 2) { i++; Console.WriteLine("當前線程ID:{0},{1}+{2}={3}", Thread.CurrentThread.ManagedThreadId, X, Y, X + Y); Thread.Sleep(1000); } } }