Task 实现多线程的模板

 

 

1.Task多线程简单模板

 

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4.  
  5. namespace Exercises
  6. {
  7.     public
    class GroupInfo
  8.     {
  9.         public
    string GroupId { get; set; }
  10.         public
    string Data { get; set; }
  11.     }
  12.  
  13.     public
    class MutilTaskTemplate
  14.     {
  15.         //执行此方法,可以看到效果
  16.         public
    void Test()
  17.         {
  18.             Run();
  19.         }
  20.  
  21.         public IEnumerable<GroupInfo> GetGroupInfos()
  22.         {
  23.             return
    new List<GroupInfo>() {
  24.                 new GroupInfo(){ GroupId = Guid.NewGuid().ToString(), Data = "what!"},
  25.                 new GroupInfo(){ GroupId = Guid.NewGuid().ToString(), Data = "hello!"},
  26.                 new GroupInfo(){ GroupId = Guid.NewGuid().ToString(), Data = "world!"},
  27.                 new GroupInfo(){ GroupId = Guid.NewGuid().ToString(), Data = "hehe!"}
  28.             };
  29.         }
  30.  
  31.         public
    void Run()
  32.         {
  33.             Console.WriteLine("start!");
  34.  
  35.             var groupInfos = GetGroupInfos();
  36.  
  37.             List<Task> groupInfoTasks = new List<Task>();
  38.             foreach (var groupInfo in groupInfos)
  39.             {
  40.                 var task = new Task((inGroupInfo) =>
  41.                 {
  42.                     ForEveryGroup(inGroupInfo as GroupInfo);
  43.                 }, groupInfo);
  44.  
  45.                 groupInfoTasks.Add(task);
  46.             }
  47.  
  48.             Parallel.ForEach(groupInfoTasks, (t) => { t.Start(); });
  49.             Task.WaitAll(groupInfoTasks.ToArray());
  50.  
  51.             Console.WriteLine("over!");
  52.         }
  53.  
  54.         private
    void ForEveryGroup(GroupInfo groupInfo)
  55.         {
  56.             Console.WriteLine();
  57.             Console.WriteLine(groupInfo.GroupId);
  58.             //use the groupInfo.Data;
  59.             Console.WriteLine(groupInfo.Data);
  60.         }
  61.     }
  62. }

 

 

执行结果:

Task 实现多线程的模板

 

 

2.Task多线程带子线程模板

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using System.Linq;
  5.  
  6. namespace Exercises
  7. {
  8.     public
    class GroupInfo2
  9.     {
  10.         public
    string GroupId { get; set; }
  11.  
  12.         public List<RealData> Datas { get; set; }
  13.     }
  14.  
  15.     public
    class RealData
  16.     {
  17.         public RealData(string name, int age)
  18.         {
  19.             this.Name = name;
  20.             this.Age = age;
  21.         }
  22.         public
    string Name { get; set; }
  23.         public
    int Age { get; set; }
  24.     }
  25.  
  26.     public
    class MutilTaskWithSubTaskTemplate
  27.     {
  28.         //执行此方法,可以看到效果
  29.         public
    void Test()
  30.         {
  31.             Run();
  32.         }
  33.  
  34.         public IEnumerable<GroupInfo2> GetGroupInfos()
  35.         {
  36.             return
    new List<GroupInfo2>() {
  37.                 new GroupInfo2(){ GroupId = Guid.NewGuid().ToString(), Datas = new List<RealData>(){
  38.                     new RealData("daniu",26),new RealData("daniu2",27),new RealData("daniu3",28)} },
  39.  
  40.                 new GroupInfo2(){ GroupId = Guid.NewGuid().ToString(), Datas = new List<RealData>(){
  41.                     new RealData("pzdn",26),new RealData("pzdn2",27)} },
  42.  
  43.                 new GroupInfo2(){ GroupId = Guid.NewGuid().ToString(), Datas = new List<RealData>(){
  44.                     new RealData("pozi",26),new RealData("pozi2",27),new RealData("pozi3",28)} },
  45.  
  46.                 new GroupInfo2(){ GroupId = Guid.NewGuid().ToString(), Datas = new List<RealData>(){
  47.                     new RealData("douzi",26),new RealData("douzi2",27),new RealData("douzi3",28)} }
  48.             };
  49.         }
  50.  
  51.         public
    void Run()
  52.         {
  53.             Console.WriteLine("start!");
  54.  
  55.             var groupInfos = GetGroupInfos();
  56.  
  57.             int splitNumber = 2; //2条数据一个Task,改变此数值,则可以控制每条子线程的执行数据量
  58.  
  59.             List<Task> groupInfoTasks = new List<Task>();
  60.             foreach (var groupInfo in groupInfos)
  61.             {
  62.                 var task = new Task((inGroupInfo) =>
  63.                 {
  64.                     int remainData = groupInfo.Datas.Count % splitNumber;
  65.                     int splits = groupInfo.Datas.Count / splitNumber + (remainData != 0 ? 1 : 0);
  66.  
  67.                     var tmpGroupInfo = inGroupInfo as GroupInfo2;
  68.  
  69.                     for (int i = 0; i < splits; i++)
  70.                     {
  71.                         bool flag = (i == splits - 1) && remainData != 0;
  72.  
  73.                         //当前分组的子线程
  74.                         var subTask = new Task((inList) =>
  75.                         {
  76.                             ForEveryGroup(groupInfo.GroupId, inList as IEnumerable<RealData>);
  77.                         }, tmpGroupInfo.Datas.Skip(splitNumber * i).Take(flag ? remainData : splitNumber), TaskCreationOptions.AttachedToParent);
  78.  
  79.                         subTask.Start();
  80.                     }
  81.  
  82.                 }, groupInfo);
  83.  
  84.                 groupInfoTasks.Add(task);
  85.             }
  86.  
  87.             Parallel.ForEach(groupInfoTasks, (t) => { t.Start(); });
  88.             try
  89.             {
  90.                 Task.WaitAll(groupInfoTasks.ToArray());
  91.             }
  92.             catch (AggregateException e)  //AggregateException可以捕获运行中出现的错误
  93.             {
  94.                 Console.WriteLine("Caught Exception:" + e.InnerException.Message); //这里显示
  95.             }
  96.  
  97.             Console.WriteLine("over!");
  98.         }
  99.  
  100.         private
    void ForEveryGroup(string groupId, IEnumerable<RealData> realDatas)
  101.         {
  102.             Console.WriteLine(groupId);
  103.             //use the groupInfo.Data;
  104.             Console.WriteLine(realDatas == null);
  105.             foreach (var item in realDatas)
  106.             {
  107.                 Console.WriteLine(item.Name + "-" + item.Age);
  108.             }
  109.         }
  110.     }
  111. }

 

 

执行结果:

Task 实现多线程的模板

 

3.加入超时

可以增加一个等待超时的字段,在Task.WaitAll(groupInfoTasks.ToArray(),timeOut);

上一篇:Codeforces Beta Round #51 B. Smallest number dfs


下一篇:PSP总结