一、场景

使用Task来进行累加操作。

二、例子-Task使用

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 using System.Threading.Tasks;
 7 
 8 namespace AsyncTask
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             Console.ForegroundColor = ConsoleColor.DarkGreen;
15             PrintThreadInfo("Print info in Main");
16             Console.ResetColor();
17             Console.WriteLine();
18             Task<int> myTask = new Task<int>(loop => AsyncMethod((int)loop), 10);
19             myTask.Start();
20             Console.WriteLine($"Result is: {myTask.Result}");//myTask.Result会阻塞当前调用线程
21             Console.WriteLine("Done!");
22         }
23         private static int AsyncMethod(int loopNum)
24         {
25             PrintThreadInfo("Print info in AsyncMethod");
26             int mySum = 0;
27             for(int i = 0; i < loopNum; i++)
28             {
29                 mySum += i;
30                 Thread.Sleep(1000);
31             }
32             return mySum;
33         }
34         private static void PrintThreadInfo(string info)
35         {
36             Console.WriteLine(info);
37             Console.WriteLine($"ThreadId:{Thread.CurrentThread.ManagedThreadId}\nIsBackgroundThread:{Thread.CurrentThread.IsBackground}\nIsThreadPoolThread:{Thread.CurrentThread.IsThreadPoolThread}");
38             int workerThread = 0;
39             int ioThread = 0;
40             ThreadPool.GetMaxThreads(out workerThread, out ioThread);
41             Console.WriteLine($"MaxWorkerThread:{workerThread}\nMaxIoThread:{ioThread}");
42             int workerThreadAvailable = 0;
43             int ioThreadAvailable = 0;
44             ThreadPool.GetAvailableThreads(out workerThreadAvailable, out ioThreadAvailable);
45             Console.WriteLine($"AvailableWorkerThread:{workerThreadAvailable}\nAvailableIoThread:{ioThreadAvailable}");
46         }
47     }
48 }
View Code

相关文章:

  • 2022-12-23
  • 2021-08-31
  • 2022-12-23
  • 2022-12-23
  • 2021-08-07
  • 2022-12-23
  • 2021-12-05
  • 2021-12-05
猜你喜欢
  • 2022-12-23
  • 2021-04-28
  • 2021-12-05
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
  • 2021-11-28
相关资源
相似解决方案