文章出處

代碼:

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

 


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()