C#創(chuàng)建線程帶參數的方法
更新時間:2016年07月27日 10:55:59 投稿:mrr
本文給大家介紹C#創(chuàng)建線程帶參數的方法,包括無參數線程的創(chuàng)建,帶一個參數線程的創(chuàng)建及帶兩個及以上參數線程的創(chuàng)建,非常不錯,具有參考借鑒價值,感興趣的朋友一起看下吧
1、無參數線程的創(chuàng)建
Thread thread = new Thread(new ThreadStart(getpic)); thread.Start(); private void showmessage() { Console.WriteLine("hello world"); }
2、帶一個參數的線程
使用ParameterizedThreadStart,調用 System.Threading.Thread.Start(System.Object) 重載方法時將包含數據的對象傳遞給線程。
注意傳遞的參數只能是object類型,不過可以進行強制類型轉換。
Thread thread = new Thread(new ParameterizedThreadStart(showmessage)); string o = "hello"; thread.Start((object)o); private static void showmessage(object message) { string temp = (string)message; Console.WriteLine(message); }
3、帶兩個及以上參數的線程
這時候可以將線程執(zhí)行的方法和參數都封裝到一個類里邊,通過實例化該類,方法就可以調用屬性來盡享傳遞參數。
例如如下程序,想傳入兩個string變量,然后打印輸出。
public class ThreadTest { private string str1; private string str2; public ThreadTest(string a, string b) { str1 = a; str2 = b; } public void ThreadProc() { Console.WriteLine(str1 + str2); } } public class Example { public static void Main() { ThreadTest tt = new ThreadTest("hello ", "world"); Thread thread = new Thread(new ThreadStart(tt.ThreadProc)); thread.Start(); } }
以上所述是小編給大家介紹的C#創(chuàng)建線程帶參數的方法 ,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!