C# -- 使用Parallel並行執行任務


C#:使用Parallel並行執行任務

1. 代碼實現

 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             TestParallel();
 6             Console.ReadKey();
 7         }
 8 
 9         static void TestParallel()
10         {
11             List<Action> listTask = new List<Action>();
12             for (int i = 0; i < 5; i++)
13             {
14                 listTask.Add(new Action(TestAction));
15             }
16             Parallel.For(0, listTask.Count, new Action<int>(i => listTask[i].Invoke()));
17 
18         }
19 
20         static void TestAction()
21         {
22             string gid = Guid.NewGuid().ToString();
23             Console.WriteLine("當前線程ID:{0},線程啟動....GID:{1}", Thread.CurrentThread.ManagedThreadId, gid);
24             Thread.Sleep(1000);
25             Console.WriteLine("當前線程ID:{0},線程結束<<<<....GID:{1}", Thread.CurrentThread.ManagedThreadId, gid);
26         }
27 
28     }

2. 運行結果:

 


免責聲明!

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



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