一.介绍
Task是.NetFramework3.0出现的,线程是基于线程池,然后提供了丰富的API. 先用AverageAssign方法把一组数据平均分成n组,再通过遍历n组数据,循环开Task多线程。
二.平均分组方法
/// <summary> /// 将一组数据平均分成n组 /// </summary> /// <param name="source">要分组的数据源</param> /// <param name="n">平均分成n组</param> /// <returns><T></returns> public static List<List<T>> AverageAssign(List<T> source, int n) { List<List<T>> result = new List<List<T>>(); int remainder = source.Count() % n; //(先计算出余数) int number = source.Count() / n; //然后是商 int offset = 0;//偏移量 for (int i = 0; i < n; i++) { List<T> value = null; if (remainder > 0) { value = source.Take((i + 1) * number + offset + 1).Skip(i * number + offset).ToList(); remainder--; offset++; } else { value = source.Take((i + 1) * number + offset).Skip(i * number + offset).ToList(); } result.Add(value); } return result; }
三.Task
string message = string.Empty; var listGroup = Test<ModelDemo>.AverageAssign(list,3); //信号量 var tokenSource = new CancellationTokenSource(); //先添加进Task数组,然后一起启动异步 //TaskFactory taskFactory = new TaskFactory(); //List<Task> taskList = new List<Task>(); //taskList.Add(taskFactory.StartNew(() => //{} // Task.WaitAll(taskList.ToArray()); try { foreach (var group in listGroup) { Task.Factory.StartNew(() => { if (tokenSource.Token.IsCancellationRequested) { Console.WriteLine("日志"); return; } //要执行的方法 Print(group); }, tokenSource.Token); } } catch (AggregateException aex) { tokenSource.Cancel(); foreach (var item in aex.InnerExceptions) { message += item.Message; } Console.WriteLine(message); } catch (Exception ex) { Console.WriteLine(ex.Message); }
static void Print(List<ModelDemo> model)
{
foreach (var item in model)
{
Console.WriteLine(item.Id);
}
}