using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Api.Framework.Utils
{
public class TaskTool
{
///
/// 最大并发
///
private int max_run { get; set; }
///
/// 任务管理器
///
public List Tasks { get; private set; }
///
/// 创建线程池
///
///
public TaskTool()
{
this.Tasks = new List();
}
///
/// 增加任务
///
///
public void AddTask(Action method)
{
Tasks.Add(new Task(method));
}
///
/// 执行线程池内所有线程
///
/// 最大并行线程数量
/// 执行完成后通知
public void Start(int max_sync, AsyncCallback callback)
{
DateTime start_Time = DateTime.Now;
Action action = delegate ()
{
//循环几次
var _count = Tasks.Count / max_sync; if (Tasks.Count % max_sync != 0) _count++;
for (int i = 0; i < _count; i++)
{
List _runs = new List();
for (int j = i * max_sync; j < Tasks.Count && _runs.Count < max_sync; j++)
{
var task = Tasks[j];
_runs.Add(task);
task.Start();
}
Task.WaitAll(_runs.ToArray());
}
};
if (callback == null) action.Invoke();
else action.BeginInvoke(callback, null);
}
public void Clear()
{
this.Tasks.Clear();
}
}
public static class TaskExtend
{
///
/// 不卡界面休眠
///
/// 源
/// 毫秒
public static void Sleep(this object obj, int millisecondsTimeout)
{
System.Threading.Thread t = new System.Threading.Thread(o => System.Threading.Thread.Sleep(millisecondsTimeout));
t.Start(obj);
while (t.IsAlive)
{
System.Windows.Forms.Application.DoEvents();
}
}
}
}