代碼: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namesp ...
代碼:
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; /// <summary> /// 線程數 /// </summary> private static int _ThreadCount = 0; private static object _Lock = new object(); private static List<Task> _TaskList = new List<Task>(); static ThreadUtil() { _ProcessorCount = Environment.ProcessorCount * 2 / 4; //使用的邏輯處理器數 if (_ProcessorCount < 1) _ProcessorCount = 1; } public static void Run(Action<object> doWork, object arg, Action<Exception> errorAction) { Task task = Task.Factory.StartNew((obj) => { while (_ThreadCount >= _ProcessorCount) { Thread.Sleep(1); } lock (_Lock) { _ThreadCount++; } try { doWork(obj); } catch (Exception ex) { errorAction(ex); } lock (_Lock) { _ThreadCount--; } }, arg); _TaskList.Add(task); } public static void WaitAll() { Task.WaitAll(_TaskList.ToArray()); } } }View Code
使用方法:
ThreadUtil.Run((obj) => { //todo },arg,(ex)=> { //錯誤處理 });View Code