/// <summary>
/// 模拟1000条数据,每条耗时1秒钟,开100个线程处理,结果耗时10秒,符合预期
/// </summary>
private void DoAction()
{
//获取待处理数据,如待同步订单,下面的list是测试数据
var list = new List<int>();
for (int i = 0; i < 1000; i++)
{
list.Add(i);
}
var ticket = Environment.TickCount;
ThreadHelper.Run(list, (a) =>
{
//处理操作,如订单同步
Thread.Sleep(1000);//这句是测试代码,模拟处理操作花费的时间
}, () =>
{
MessageBox.Show("全部完成,耗时:" + (Environment.TickCount - ticket) + "毫秒");
Thread.Sleep(5000);//加了延时,防止数据库没有待同步订单时无限查询数据库
DoAction();//开始下一次同步
},100);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items">待处理的数据集合</param>
/// <param name="action">处理操作</param>
/// <param name="finish">完成后的操作</param>
/// <param name="threadCount">线程数量</param>
public static void Run<T>(List<T> items, Action<T> action, Action finish, int threadCount = 100)
{
_finishedCount = 0;
var perCount = items.Count < threadCount ? items.Count : items.Count / threadCount;
var index = 0;
while (true)
{
var ps = items.Skip(index * perCount).Take(perCount).ToList();
if (!ps.Any())
return;
new Thread(() =>
{
foreach (var p in ps)
{
action(p);
lock (_lock)
{
_finishedCount++;
}
if (_finishedCount == items.Count)
finish?.Invoke();
}
}).Start();
index++;
}
}