经典多线程任务分发合并模型

Posted on 2013-12-24 14:15  xiaomaogong  阅读(556)  评论(0编辑  收藏  举报

最近写了个关于多线程的分发合并代码:

 1 public static string GetCSVStringFromFacotry(int MaximumCurveNumber,IEmerable<IData> revertEligible)
 2     {
 3         int currenttotalNumverOfCurve = revertEligible.Count();
 4         List<Task> tasks = new List<Task>();
 5         int startIndex = 0;
 6         while (currenttotalNumverOfCurve > 0)
 7         {
 8             List<IData> currentExecuteCurveList = new List<IData>();
 9             for (int i = startIndex; i < startIndex + MaximumCurveNumber; i++)
10             {
11                 if(revertEligible.Count() > i)
12                     currentExecuteCurveList.Add(revertEligible.ElementAt(i));
13             }
14 
15             tasks.Add(Task.Factory.StartNew
16                 (
17                 () =>
18                 {
19                     string content = GetOneTimeCSVStringFromFacotry(currentExecuteCurveList);
20                     //Remove header
21                     lock (result)
22                     {
23                         if (!string.IsNullOrWhiteSpace(result))
24                         {
25                             //Remove header
26                             content = RemoveCSVHeader(content);
27                         }
28                         result += content;
29                     }
30                 }
31             ));
32             currenttotalNumverOfCurve -= MaximumCurveNumber;
33             startIndex += MaximumCurveNumber;
34         }
35         try
36         {
37             Task.WaitAll(tasks.ToArray());
38         }
39         catch (AggregateException ae)
40         {
41             foreach (var innerException in ae.InnerExceptions)
42             {
43                 log.Error("Exception in GetCSVStringFromFacotry", innerException);
44             }
45         }
46         return result;
47     }

 

Copyright © 2024 xiaomaogong
Powered by .NET 9.0 on Kubernetes