public class TaskHelper
{
private static int ThreadCount = 0;
private static int ThreadMax = 5;
private static object _lockObject = new object();
/// <summary>
/// 并行执行多个方法
/// </summary>
/// <param name="action"></param>
private static void ActionAsParallel(params Action[] action)
{
return;
bool enableParallel = false;
lock (_lockObject)
{
if (ThreadMax - ThreadCount < action.Length)
{
enableParallel = true;
ThreadCount = ThreadCount + 5;
}
else
{
enableParallel = false;
}
}
action.AsParallel();
}
/// <summary>
/// 并发执行请求
/// </summary>
public static Dictionary<string, object> Batch(Dictionary<string, Func<object>> funcs)
{
var result = new Dictionary<string, object>();
using (var countdown = new MutipleThreadResetEvent(funcs.Count))
{
foreach (var func in funcs)
{
//开启N个线程,传递MutipleThreadResetEvent对象给子线程
ThreadPool.QueueUserWorkItem((t) =>
{
func.Value.Invoke();
result.Add(func.Key, func.Value.Invoke());
MutipleThreadResetEvent ctd = t as MutipleThreadResetEvent;
//发送信号量 本线程执行完毕
countdown.SetOne();
}, countdown);
}
//等待所有线程执行完毕
countdown.WaitAll();
}
return result;
}
/// <summary>
/// 无返回值,并发方法委托
/// </summary>
/// <param name="funcs"></param>
public static void Batch(params Action[] funcs)
{
using (var countdown = new MutipleThreadResetEvent(funcs.Length))
{
foreach (var func in funcs)
{
//开启N个线程,传递MutipleThreadResetEvent对象给子线程
ThreadPool.QueueUserWorkItem((t) =>
{
func();
MutipleThreadResetEvent ctd = t as MutipleThreadResetEvent;
//发送信号量 本线程执行完毕
countdown.SetOne();
}, countdown);
}
//等待所有线程执行完毕
countdown.WaitAll();
}
}
}
/// <summary>
/// 封装ManualResetEvent
/// </summary>
public class MutipleThreadResetEvent : IDisposable
{
private readonly ManualResetEvent done;
private readonly int total;
private long current;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="total">需要等待执行的线程总数</param>
public MutipleThreadResetEvent(int total)
{
this.total = total;
current = total;
done = new ManualResetEvent(false);
}
/// <summary>
/// 唤醒一个等待的线程
/// </summary>
public void SetOne()
{
// Interlocked 原子操作类 ,此处将计数器减1
if (Interlocked.Decrement(ref current) == 0)
{
//当所有等待线程执行完毕时,唤醒等待的线程
done.Set();
}
}
/// <summary>
/// 等待所有线程执行完毕
/// </summary>
public void WaitAll()
{
done.WaitOne();
}
/// <summary>
/// 释放对象占用的空间
/// </summary>
public void Dispose()
{
((IDisposable)done).Dispose();
}