代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Utils
{
/// <summary>
/// 线程工具类
/// </summary>
public class ThreadUtil
{
/// <summary>
/// 使用的逻辑处理器数
/// </summary>
private static int _ProcessorCount;
private static Semaphore _semaphore;
private static List<Task> _TaskList = new List<Task>();
private static object _lock = new object();
static ThreadUtil()
{
_ProcessorCount = Environment.ProcessorCount * 2 / 4; //使用的逻辑处理器数
if (_ProcessorCount < 1) _ProcessorCount = 1;
_semaphore = new Semaphore(_ProcessorCount, _ProcessorCount);
}
public static void Run(Action<object> doWork, object arg, Action<Exception> errorAction)
{
Task task = null;
task = Task.Factory.StartNew((obj) =>
{
_semaphore.WaitOne();
try
{
doWork(obj);
}
catch (Exception ex)
{
errorAction(ex);
}
_semaphore.Release();
lock (_lock)
{
_TaskList.Remove(task);
}
}, arg);
lock (_lock)
{
_TaskList.Add(task);
}
}
public static void WaitAll()
{
Task.WaitAll(_TaskList.ToArray());
}
}
}
View Code
使用方法:
ThreadUtil.Run((obj) =>
{
//todo
},arg,(ex)=>
{
//错误处理
});
View Code