ljchengx
2021-07-31 08:27:00 +08:00
之前处理过,大批量的数据同步操作,也用到了 Task,写了两个例子 可以参考下,希望有帮助:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class Program
{
public static bool _go = true;
public static int currentTeacherCount = 0;
public static int maxTask = 15;
public static object obj = new object();
static void Main(string[] args)
{
List<Task> tasks = new List<Task>();
List<String> list = new List<string>();
list.Add("1");
list.Add("2");
list.Add("3");
list.Add("4");
foreach (var item in list)
{
tasks.Add(Task.Factory.StartNew(() =>
{
Log(item);
}).ContinueWith(t =>
{
lock (obj)
{
Interlocked.Increment(ref currentTeacherCount);
Console.WriteLine("第" + currentTeacherCount + "数据同步完成,共" + list.Count() + "数据需要处理");
}
}));
if (tasks.Count >= maxTask)
{
Task.WaitAny(tasks.ToArray());
tasks = tasks.Where(t => t.Status == TaskStatus.Running).ToList();
}
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine("所有线程结束!");
Console.ReadLine();
}
public static void Log(String str)
{
Console.WriteLine("开始处理第" + str + "个");
}
}
}