using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace ATest { class A { public static void Main() { Thread t = new Thread(new ThreadStart(A)); t.Start(); Console.Read(); } private static void A() { Console.WriteLine("不帶參數 A!"); } } }結果顯示“不帶參數 A!”
由於ParameterizedThreadStart要求參數類型必須為object,所以定義的方法B形參類型必須為object。
123456789101112131415161718192021222324using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace BTest { class B { public static void Main() { Thread t = new Thread(new ParameterizedThreadStart(B)); t.Start("B"); Console.Read(); } private static void B(object obj) { Console.WriteLine("帶一個參數 {0}!",obj.ToString ()); } } }結果顯示“帶一個參數 B!”
三、帶多個參數創建Thread
由於Thread默認只提供了這兩種構造函數,如果需要傳遞多個參數,可以基於第二種方法,將參數作為類的屬性傳給線程。
1234567891011121314151617181920212223242526272829303132using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace CTest { class C { public static void Main() { MyParam m = new MyParam(); m.x = 6; m.y = 9; Thread t = new Thread(new ThreadStart(m.Test)); t.Start(); Console.Read(); } } class MyParam { public int x, y; public void Test() { Console.WriteLine("x={0},y={1}", this.x, this.y); } } }結果顯示“x=6,y=9”
四、利用回調函數給主線程傳遞參數