//控制下Task的20个并发数量,
List<Task> taskList = new List<Task>();
for (int i = 0; i < 10000; i++)
{
int k = i;
if (taskList.Count(t => t.Status != TaskStatus.RanToCompletion) >= 20)
{
Task.WaitAny(taskList.ToArray());
taskList = taskList.Where(t => t.Status != TaskStatus.RanToCompletion).ToList();
}
taskList.Add(Task.Run(() =>
{
Console.WriteLine($"This is {k} running ThreadId={Thread.CurrentThread.ManagedThreadId.ToString("00")}");
Thread.Sleep(2000);
}));
}
//taskList 全部子线程执行完后,获取所有返回的值
for(int i=0;i<taskList .count();i++)
{
var result= taskList[i].result;
}
------demo-------
//循环List,启用20个线程去执行计算每个item的销售价格,全部销售价格计算完成,返回销售价格;
public static void Show()
{
List<Task> taskList = new List<Task>();
int skuList = 10000;
for (int i = 0; i < skuList; i++)
{
try
{
int k = i;
if (taskList.Count(t => t.Status != TaskStatus.RanToCompletion) >= 20)
{
Task.WaitAny(taskList.ToArray());
taskList = taskList.Where(t => t.Status != TaskStatus.RanToCompletion).ToList();
}
taskList.Add(Task.Run(() =>
{
var result = GetCalculator(k, Thread.CurrentThread.ManagedThreadId.ToString());
}));
}
catch(Exception ex)
{
//throw ex
}
}
Task.WaitAll(taskList.ToArray());
//taskList 全部子线程执行完后,获取所有list返回的值
for (int i = 0; i < list.Count(); i++)
{
var result = list[i];
}
}
public static List<string> GetCalculator(int i,string id)
{
lock (Lock)
{
list.Add(i.ToString() + "_Thread_" + id);
}
return list;
}