ThreadStart:
ThreadStart這個委托定義為void ThreadStart(),也就是說,所執行的方法不能有參數。
ThreadStart threadStart=new ThreadStart(Calculate); Thread thread=new Thread(threadStart); thread.Start(); public void Calculate() { double Diameter=0.5; Console.Write("The Area Of Circle with a Diameter of {0} is {1}"Diameter,Diameter*Math.PI); }
這裡我們用定義了一個ThreadStart類型的委托,這個委托制定了線程需要執行的方法: Calculate,在這個方法裡計算了一個直徑為0.5的圓的周長,並輸出.這就構成了最簡單的多線程的例子,在很多情況下這就夠用了
ParameterThreadStart:
ParameterThreadStart的定義為void ParameterizedThreadStart(object state),使用這個這個委托定義的線程的啟動函數可以接受一個輸入參數,具體例子如下 :
ParameterizedThreadStart threadStart=new ParameterizedThreadStart(Calculate) Thread thread=new Thread() ; thread.Start(0.9); public void Calculate(object arg) { double Diameter=double(arg); Console.Write("The Area Of Circle with a Diameter of {0} is {1}"Diameter,Diameter*Math.PI); }
Calculate方法有一個為object類型的參數,雖然只有一個參數,而且還是object類型的,使用的時候尚需要類型轉換,但是好在可以有參數了,並且通過把多個參數組合到一個類中,然後把這個類的實例作為參數傳遞,就可以實現多個參數傳遞.比如:
class AddParams { public int a, b; public AddParams(int numb1, int numb2) { a = numb1; b = numb2; } } #endregion class Program { static void Main(string[] args) { Console.WriteLine("***** Adding with Thread objects *****"); Console.WriteLine("ID of thread in Main(): {0}", Thread.CurrentThread.ManagedThreadId); AddParams ap = new AddParams(10, 10); Thread t = new Thread(new ParameterizedThreadStart(Add)); t.Start(ap); Console.ReadLine(); } #region Add method static void Add(object data) { if (data is AddParams) { Console.WriteLine("ID of thread in Main(): {0}", Thread.CurrentThread.ManagedThreadId); AddParams ap = (AddParams)data; Console.WriteLine("{0} + {1} is {2}", ap.a, ap.b, ap.a + ap.b); } } #endregion } }