C#多线程编程Task用法详解

  using System;

  using System.Collections.Generic;

  using System.Linq;

  using System.Threading;

  using System.Threading.Tasks;

  namespace TaskDemo

  {

  class Program

  {

  static void Main(string[] args)

  {

  #region 1、使用Task创建任务

  //Task task = new Task(() => TaskMethod("Task 1"));

  //Console.WriteLine("before start status:"+task.Status);

  //// Task创建的任务必须调用start方法才能启动

  //task.Start();

  //Console.WriteLine("after start status:" + task.Status);

  #endregion

  #region 2、使用Task.Run创建任务

  // Task.Run(() => TaskMethod("Task Run"));

  #endregion

  #region 3、使用Factory创建任务

  // 使用Task.Factory创建

  //Task.Factory.StartNew(() => TaskMethod("Task 4"));

  ////标记为长时间运行任务,则任务不会使用线程池,而在单独的线程中运行。

  //Task.Factory.StartNew(() => TaskMethod("Task 5"), TaskCreationOptions.LongRunning);

  // 实例化TaskFactory对象,然后创建

  //TaskFactory factory = new TaskFactory();

  //factory.StartNew(() => TaskMethod("Task 6"));

  #endregion

  #region 4、创建带返回值的任务

  //TaskMethodReturn("Main Thread Task");

  //// 创建带返回值的Task

  //Task task = CreateTask("Task 1");

  //// 启动

  //task.Start();

  //// 获取返回值

  //int result1 = task.Result;

  //Console.WriteLine($"Task 1 Result is:{result1}");

  //Task task2 = new Task(() => TaskMethodReturn("Task 2"));

  //task2.Start();

  //int result2 = task2.Result;

  //Console.WriteLine($"Task 2 Result is:{result2}");

  //int result3= Task.Run(() => TaskMethodReturn("Task 3")).Result;

  //Console.WriteLine($"Task 3 Result is:{result3}");

  //int result4 = Task.Factory.StartNew(() => TaskMethodReturn("Task 4")).Result;

  //Console.WriteLine($"Task 4 Result is:{result4}");

  #endregion

  #region 测试Task线程是来自于ThreadPool

  // Test();

  #endregion

  // 合作开发项目,每个人负责一个模块,可以认为是多线程

  // 无序

  //Console.WriteLine("开始合作开发一个大项目!");

  //Task.Run(() => CodingShow("Tom", "搭建微服务架构!"));

  //Task.Run(() => CodingShow("Kevin", "微信接口!"));

  //Task.Run(() => CodingShow("Jack", "搭建后台框架!"));

  //Task.Run(() => CodingShow("Alex", "设计数据库!"));

  //Task.Run(() => CodingShow("Lee", "支付宝接口对接!"));

  //Console.WriteLine("所有模块都开发完成,开始搭建测试环境");

  #region WaitAll

  //// 定义一个Task类型的集合

  //List taskList = new List();

  //Console.WriteLine("开始合作开发一个大项目!");

  //taskList.Add(Task.Run(() => CodingShow("Tom", "搭建微服务架构!")));

  //taskList.Add(Task.Run(() => CodingShow("Kevin", "微信接口!")));

  //taskList.Add(Task.Run(() => CodingShow("Jack", "搭建后台框架!")));

  //taskList.Add(Task.Run(() => CodingShow("Alex", "设计数据库!")));

  //taskList.Add(Task.Run(() => CodingShow("Lee", "支付宝接口对接!")));

  //// 等待所有模块都开发完成,才能搭建测试环境

  //Task.WaitAll(taskList.ToArray());

  //Console.WriteLine("所有模块都开发完成,开始搭建测试环境");

  #endregion

  #region WaitAny

  // 定义一个Task类型的集合

  //List taskList = new List();

  //Console.WriteLine("开始合作开发一个大项目!");

  //taskList.Add(Task.Run(() => CodingShow("Tom", "搭建微服务架构!")));

  //taskList.Add(Task.Run(() => CodingShow("Kevin", "微信接口!")));

  //taskList.Add(Task.Run(() => CodingShow("Jack", "搭建后台框架!")));

  //taskList.Add(Task.Run(() => CodingShow("Alex", "设计数据库!")));

  //taskList.Add(Task.Run(() => CodingShow("Lee", "支付宝接口对接!")));

  //// 等待所有模块都开发完成,才能搭建测试环境

  //Task.WaitAny(taskList.ToArray());

  //Console.WriteLine("有模块开发完成,开始搭建测试环境");

  #endregion

  #region ContinueWhenAll

  //List taskList = new List();

  //Console.WriteLine("开始合作开发一个大项目!");

  //taskList.Add(Task.Run(() => CodingShow("Tom", "搭建微服务架构!")));

  //taskList.Add(Task.Run(() => CodingShow("Kevin", "微信接口!")));

  //taskList.Add(Task.Run(() => CodingShow("Jack", "搭建后台框架!")));

  //taskList.Add(Task.Run(() => CodingShow("Alex", "设计数据库!")));

  //taskList.Add(Task.Run(() => CodingShow("Lee", "支付宝接口对接!")));

  //TaskFactory factory = new TaskFactory();

  //factory.ContinueWhenAll(taskList.ToArray(), t => Console.WriteLine("所有模块开发完成"));

  #endregion

  #region ContinueWhenAll

  //List taskList = new List();

  //Console.WriteLine("开始合作开发一个大项目!");

  //taskList.Add(Task.Run(() => CodingShow("Tom", "搭建微服务架构!")));

  //taskList.Add(Task.Run(() => CodingShow("Kevin", "微信接口!")));

  //taskList.Add(Task.Run(() => CodingShow("Jack", "搭建后台框架!")));

  //taskList.Add(Task.Run(() => CodingShow("Alex", "设计数据库!")));

  //taskList.Add(Task.Run(() => CodingShow("Lee", "支付宝接口对接!")));

  //TaskFactory factory = new TaskFactory();

  //factory.ContinueWhenAny(taskList.ToArray(), t => Console.WriteLine("某一个模块开发完成"));

  #endregion

  #region ContinueWith

  Task.Run(() => { Console.WriteLine("任务执行完成"); }).ContinueWith(p=>

  {

  Task.Run(() => { Console.WriteLine("执行回调"); });

  });

  #endregion

  Console.ReadKey();

  }

  ///

  /// 返回一个Task

  ///

  ///

  ///

  static Task CreateTask(string name)

  {

  // 参数是Func

  return new Task(() => TaskMethodReturn(name));

  }

  static void TaskMethod(string name)

  {

  Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",

  name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);

  }

  static int TaskMethodReturn(string name)

  {

  Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",

  name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);

  Thread.Sleep(TimeSpan.FromSeconds(2));

  return 42;

  }

  ///

  /// 测试Task的线程来自于ThreadPool

  ///

  static void Test()

  {

  // 设置线程池中最大的线程数

  ThreadPool.SetMaxThreads(6, 6);

  // 创建Task的集合

  List taskList = new List();

  // 创建int类型的集合,用于存放线程ID

  List threadIdList = new List();

  // 使用Task循环创建50个线程

  for (int i = 0; i < 30; i++)

  {

  int k = i;

  Task task = Task.Run(() =>

  {

  // 当前线程ID加入到集合中

  threadIdList.Add(Thread.CurrentThread.ManagedThreadId);

  Console.WriteLine($"this is {k} 循环 ThreadID:{Thread.CurrentThread.ManagedThreadId.ToString("00")}");

  // 休眠

  Thread.Sleep(200);

  });

  // 把task加入到集合中

  taskList.Add(task);

  }

  // 等待所有的线程执行完

  Task.WaitAll(taskList.ToArray());

  // 输出总数量

  Console.WriteLine($"线程总数:{threadIdList.Distinct().Count()}");

  }

  ///

  /// 模拟Coding过程

  ///

  ///

  ///

  static void CodingShow(string name, string projectName)

  {

  Console.WriteLine($"CodingShow Start {name} {projectName} {Thread.CurrentThread.ManagedThreadId.ToString("00")} ");

  long lResult = 0;

  for (int i = 0; i < 1_000_000_000; i++)

  {

  lResult += i;

  }

  Console.WriteLine($"CodingShow End {name} {projectName} {Thread.CurrentThread.ManagedThreadId.ToString("00")} ");

  }

  }

  }