一、场景

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

注: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 }

运行结果如下:

四、例子-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 }

最新文章

  1. javascript 日期转换为中文
  2. 《DSP using MATLAB》为什么要z变换?
  3. python爬虫系列之爬京东手机数据
  4. CF #CROC 2016 - Elimination Round D. Robot Rapping Results Report 二分+拓扑排序
  5. dede系统自定义变量删除方法
  6. 常用的前端相关chrome插件
  7. css3整理--media
  8. U盘安装ubuntu 16.04 遇到 gfxboot.c32:not a COM32R image boot 的解决方法
  9. struts2实现XML异步交互
  10. Linux使用sshfs挂载远程目录到本地
  11. hdoj 1004 学习思路
  12. WPF使用DataGridComboBoxColumn完成绑定
  13. 字符串格式化格式 -- Numeric Format Strings
  14. 【Intel AF 2.1 学习笔记二】AF中的页面——Panel
  15. jenkins 执行python脚本 断言失败就可以构建失败
  16. 简单版AC自动机
  17. 在EC2上创建root用户,并使用root用户登录
  18. HDUOJ--1874 畅通工程续
  19. 3.1 High Availability
  20. 51nod1981 如何愉快地与STL玩耍

热门文章

  1. WIN10家庭版 访问WINXP 共享打印机
  2. VBA:考场场标打印
  3. keeplived+mycat+mysql高可用读写分离水平分表(谁看谁都会)
  4. pagehelper插件使用时查询不到数据
  5. 前端开发入门到进阶第三集【Jsonp】
  6. 微信小程序云开发-数据库和云函数的应用-点赞/收藏/评论功能
  7. 为什么每次下载后必须关闭掉IO流(十五)
  8. Docker run 命令参数及使用
  9. [源码解析] 机器学习参数服务器ps-lite 之(3) ----- 代理人Customer
  10. 95后新同事年薪35W+,老员工却“自愿申请”降薪10%,中年职场人正在崩溃