ThreadStart:
ThreadStart這個委托定義為void ThreadStart(),也就是說,所執(zhí)行的方法不能有參數(shù)。
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類型的委托,這個委托制定了線程需要執(zhí)行的方法: Calculate,在這個方法里計算了一個直徑為0.5的圓的周長,并輸出.這就構(gòu)成了最簡單的多線程的例子,在很多情況下這就夠用了
ParameterThreadStart:
ParameterThreadStart的定義為void ParameterizedThreadStart(object state),使用這個這個委托定義的線程的啟動函數(shù)可以接受一個輸入?yún)?shù),具體例子如下 :
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類型的參數(shù),雖然只有一個參數(shù),而且還是object類型的,使用的時候尚需要類型轉(zhuǎn)換,但是好在可以有參數(shù)了,并且通過把多個參數(shù)組合到一個類中,然后把這個類的實例作為參數(shù)傳遞,就可以實現(xiàn)多個參數(shù)傳遞.比如:
class AddParams{ public int a, b; public AddParams(int numb1, int numb2) { a = numb1; b = numb2; }}#endregionclass 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}}新聞熱點
疑難解答