• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#多线程---Task实现异步

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

一、场景

使用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

注:myTask.Result会阻塞当前调用线程

运行结果如下:

 

三、例子-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             CancellationTokenSource cts = new CancellationTokenSource();
19             Task<int> myTask = new Task<int>(loop => AsyncMethod((int)loop,cts.Token), 10);
20             myTask.Start();
21 
22             //Thread.Sleep(3000);
23             //cts.Cancel();
24             cts.CancelAfter(3 * 1000);
25             Console.WriteLine($"Result is: {myTask.Result}");//myTask.Result会阻塞当前调用线程
26             Console.WriteLine("Done!");
27         }
28         private static int AsyncMethod(int loopNum, CancellationToken ct)
29         {
30             PrintThreadInfo("Print info in AsyncMethod");
31             int mySum = 0;
32             try {
33                 for (int i = 0; i < loopNum; i++)
34                 {
35                     ct.ThrowIfCancellationRequested();
36                     mySum += i;
37                     Thread.Sleep(1000);
38                 }
39             }
40             catch(Exception e)
41             {
42                 Console.ForegroundColor = ConsoleColor.Red;
43                 Console.WriteLine("Exception type:" + e.GetType().Name);
44                 Console.WriteLine("Operation is Canceled");
45                 Console.ResetColor();
46             }
47             return mySum;
48         }
49         private static void PrintThreadInfo(string info)
50         {
51             Console.WriteLine(info);
52             Console.WriteLine($"ThreadId:{Thread.CurrentThread.ManagedThreadId}\nIsBackgroundThread:{Thread.CurrentThread.IsBackground}\nIsThreadPoolThread:{Thread.CurrentThread.IsThreadPoolThread}");
53             int workerThread = 0;
54             int ioThread = 0;
55             ThreadPool.GetMaxThreads(out workerThread, out ioThread);
56             Console.WriteLine($"MaxWorkerThread:{workerThread}\nMaxIoThread:{ioThread}");
57             int workerThreadAvailable = 0;
58             int ioThreadAvailable = 0;
59             ThreadPool.GetAvailableThreads(out workerThreadAvailable, out ioThreadAvailable);
60             Console.WriteLine($"AvailableWorkerThread:{workerThreadAvailable}\nAvailableIoThread:{ioThreadAvailable}");
61         }
62     }
63 }
View Code

运行结果如下:

 

四、例子-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             CancellationTokenSource cts = new CancellationTokenSource();
19             //Task<int> myTask = new Task<int>(loop => AsyncMethod((int)loop,cts.Token), 10);
20             //myTask.Start();
21 
22             Task<int> myTask = Task.Factory.StartNew(loop => AsyncMethod((int)loop, cts.Token), 10);
23 
24             //Thread.Sleep(3000);
25             //cts.Cancel();
26             cts.CancelAfter(3 * 1000);
27             Console.WriteLine($"Result is: {myTask.Result}");//myTask.Result会阻塞当前调用线程
28             Console.WriteLine("Done!");
29         }
30         private static int AsyncMethod(int loopNum, CancellationToken ct)
31         {
32             PrintThreadInfo("Print info in AsyncMethod");
33             int mySum = 0;
34             try {
35                 for (int i = 0; i < loopNum; i++)
36                 {
37                     ct.ThrowIfCancellationRequested();
38                     mySum += i;
39                     Thread.Sleep(1000);
40                 }
41             }
42             catch(Exception e)
43             {
44                 Console.ForegroundColor = ConsoleColor.Red;
45                 Console.WriteLine("Exception type:" + e.GetType().Name);
46                 Console.WriteLine("Operation is Canceled");
47                 Console.ResetColor();
48             }
49             return mySum;
50         }
51         private static void PrintThreadInfo(string info)
52         {
53             Console.WriteLine(info);
54             Console.WriteLine($"ThreadId:{Thread.CurrentThread.ManagedThreadId}\nIsBackgroundThread:{Thread.CurrentThread.IsBackground}\nIsThreadPoolThread:{Thread.CurrentThread.IsThreadPoolThread}");
55             int workerThread = 0;
56             int ioThread = 0;
57             ThreadPool.GetMaxThreads(out workerThread, out ioThread);
58             Console.WriteLine($"MaxWorkerThread:{workerThread}\nMaxIoThread:{ioThread}");
59             int workerThreadAvailable = 0;
60             int ioThreadAvailable = 0;
61             ThreadPool.GetAvailableThreads(out workerThreadAvailable, out ioThreadAvailable);
62             Console.WriteLine($"AvailableWorkerThread:{workerThreadAvailable}\nAvailableIoThread:{ioThreadAvailable}");
63         }
64     }
65 }
View Code

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#类型转换问题发布时间:2022-07-14
下一篇:
(转)经典C++库发布时间:2022-07-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap