C# 開啟線程的幾種方式


1.異步委托開啟線程

 1 public static void Main(string[] args)  2 {  3    Action<int,int> a=add;  4    a.BeginInvoke(3,4,null,null);//前兩個是add方法的參數,后兩個可以為空
 5    Console.WriteLine("main()");  6    Console.ReadKey();  7 }  8 static void add(int a,int b)  9 { 10    Console.WriteLine(a+b); 11 }

2.通過Thread類開啟線程

 1 public class Program  2  {  3         public static void Main(string[] args)  4  {  5  Thread t1;  6  Thread t2;  7             t1 = new Thread(SetInfo1);  8             t2 = new Thread(SetInfo2);  9  t1.Start(); 10             //線程睡眠 11             //t1.Join(1000); 12             //掛起線程
13  t1.Suspend(); 14             //繼續執行線程
15  t1.Resume(); 16             //結束線程 17             //t1.Abort();
18 
19  t2.Start(); 20  Console.ReadKey(); 21  } 22         //奇數線程
23         public static void SetInfo1() 24  { 25             for (int i = 0; i < 100; i++) 26  { 27                 if (i % 2 != 0) 28  { 29                     Console.WriteLine("奇數為" + i); 30  } 31  } 32  } 33         //偶數線程
34         public static void SetInfo2() 35  { 36             for (int i = 0; i < 100; i++) 37  { 38                 if (i % 2 == 0) 39  { 40                     Console.WriteLine("偶數為" + i); 41  } 42  } 43  } 44     }

3.通過線程池開啟線程

 1    //線程池可以看做容納線程的容器;一個應用程序最多只能有一個線程池;ThreadPool靜態類通過QueueUserWorkItem()方法將工作函數排入線程池; 每排入一個工作函數,就相當於請求創建一個線程;  2     //線程池的作用:  3     //1、線程池是為突然大量爆發的線程設計的,通過有限的幾個固定線程為大量的操作服務,減少了創建和銷毀線程所需的時間,從而提高效率。  4     //2、如果一個線程的時間非常長,就沒必要用線程池了(不是不能作長時間操作,而是不宜。),況且我們還不能控制線程池中線程的開始、掛起、和中止
 5     public class Program  6  {  7         public static void Main(string[] args)  8  {  9             ThreadPool.QueueUserWorkItem(new WaitCallback(TestThreadPool), new string[] { "hjh" }); 10  Console.ReadKey(); 11  } 12         public static void TestThreadPool(object state) 13  { 14             string[] arry = state as string[];//傳過來的參數值
15             int workerThreads = 0; 16             int CompletionPortThreads = 0; 17             ThreadPool.GetMaxThreads(out workerThreads, out CompletionPortThreads); 18             Console.WriteLine(DateTime.Now.ToString() + "---" + arry[0] + "--workerThreads=" + workerThreads + "--CompletionPortThreads" + CompletionPortThreads); 19  } 20     }

4.通過任務Task開啟線程

 1 public class Program  2  {  3         public static void Main(string[] args)  4  {  5             Task task = new Task(DownLoadFile_My);  6  task.Start();  7  Console.ReadKey();  8  }  9         static void DownLoadFile_My() 10  { 11             Console.WriteLine("開始下載...線程ID:"+Thread.CurrentThread.ManagedThreadId); 12             Thread.Sleep(500); 13             Console.WriteLine("下載完成!"); 14  } 15     }
 1 new Thread(() =>
 2 {
 3     try
 4     {
 5         //運行的代碼
 6     }
 7      catch (Exception ex)
 8     {
 9     }
10 }).Start();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM