主頁 > .NET開發 > C# 擴展TaskScheduler實作獨立執行緒池,支持多任務批量處理,互不干擾,無縫兼容Task

C# 擴展TaskScheduler實作獨立執行緒池,支持多任務批量處理,互不干擾,無縫兼容Task

2020-09-13 11:28:28 .NET開發

    為什么撰寫TaskSchedulerEx類?

    因為.NET默認執行緒池只有一個執行緒池,如果某個批量任務一直占著大量執行緒,甚至耗盡默認執行緒池,則會嚴重影回應用程式域中其它任務或批量任務的性能,

     特點:

    1、使用獨立執行緒池,執行緒池中執行緒分為核心執行緒和輔助執行緒,輔助執行緒會動態增加和釋放,且總執行緒數不大于引數_maxThreadCount

    2、無縫兼容Task,使用上和Task一樣,可以用它來實作異步,參見:C# async await 異步執行方法封裝 替代 BackgroundWorker

    3、佇列中尚未執行的任務可以取消

    4、通過擴展類TaskHelper實作任務分組

    5、和SmartThreadPool對比,優點是無縫兼容Task類,和Task類使用沒有區別,因為它本身就是對Task、TaskScheduler的擴展,所以Task類的ContinueWith、WaitAll等方法它都支持,以及兼容async、await異步編程

    6、代碼量相當精簡,TaskSchedulerEx類只有260多行代碼

    7、池中的執行緒數量會根據負載自動增減,支持,但沒有SmartThreadPool智能,為了性能,使用了比較笨的方式實作,不知道大家有沒有既智能,性能又高的方案,我有一個思路,在定時器中計算每個任務執行平均耗時,然后使用公式(執行緒數 = CPU核心數 * ( 本地計算時間 + 等待時間 ) / 本地計算時間)來計算最佳執行緒數,然后按最佳執行緒數來動態創建執行緒,但這個計算程序可能會犧牲性能

     對比SmartThreadPool:

    TaskSchedulerEx類代碼(使用Semaphore實作):

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Utils
{
    /// <summary>
    /// TaskScheduler擴展
    /// 每個實體都是獨立執行緒池
    /// </summary>
    public class TaskSchedulerEx : TaskScheduler, IDisposable
    {
        #region 外部方法
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
        #endregion

        #region 變數屬性事件
        private ConcurrentQueue<Task> _tasks = new ConcurrentQueue<Task>();
        private int _coreThreadCount = 0;
        private int _maxThreadCount = 0;
        private int _auxiliaryThreadTimeOut = 20000; //輔助執行緒釋放時間
        private int _activeThreadCount = 0;
        private System.Timers.Timer _timer;
        private object _lockCreateTimer = new object();
        private bool _run = true;
        private Semaphore _sem = null;
        private int _semMaxCount = int.MaxValue; //可以同時授予的信號量的最大請求數
        private int _semCount = 0; //可用信號量請求數
        private int _runCount = 0; //正在執行的和等待執行的任務數量

        /// <summary>
        /// 活躍執行緒數
        /// </summary>
        public int ActiveThreadCount
        {
            get { return _activeThreadCount; }
        }

        /// <summary>
        /// 核心執行緒數
        /// </summary>
        public int CoreThreadCount
        {
            get { return _coreThreadCount; }
        }

        /// <summary>
        /// 最大執行緒數
        /// </summary>
        public int MaxThreadCount
        {
            get { return _maxThreadCount; }
        }
        #endregion

        #region 建構式
        /// <summary>
        /// TaskScheduler擴展
        /// 每個實體都是獨立執行緒池
        /// </summary>
        /// <param name="coreThreadCount">核心執行緒數(大于或等于0,不宜過大)(如果是一次性使用,則設定為0比較合適)</param>
        /// <param name="maxThreadCount">最大執行緒數</param>
        public TaskSchedulerEx(int coreThreadCount = 10, int maxThreadCount = 20)
        {
            _sem = new Semaphore(0, _semMaxCount);
            _maxThreadCount = maxThreadCount;
            CreateCoreThreads(coreThreadCount);
        }
        #endregion

        #region override GetScheduledTasks
        protected override IEnumerable<Task> GetScheduledTasks()
        {
            return _tasks;
        }
        #endregion

        #region override TryExecuteTaskInline
        protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
        {
            return false;
        }
        #endregion

        #region override QueueTask
        protected override void QueueTask(Task task)
        {
            _tasks.Enqueue(task);

            while (_semCount >= _semMaxCount) //信號量已滿,等待
            {
                Thread.Sleep(1);
            }

            _sem.Release();
            Interlocked.Increment(ref _semCount);

            Interlocked.Increment(ref _runCount);
            if (_activeThreadCount < _maxThreadCount && _activeThreadCount < _runCount)
            {
                CreateThread();
            }
        }
        #endregion

        #region 資源釋放
        /// <summary>
        /// 資源釋放
        /// 佇列中尚未執行的任務不再執行
        /// </summary>
        public void Dispose()
        {
            _run = false;

            if (_timer != null)
            {
                _timer.Stop();
                _timer.Dispose();
                _timer = null;
            }

            while (_activeThreadCount > 0)
            {
                _sem.Release();
                Interlocked.Increment(ref _semCount);
            }
        }
        #endregion

        #region 創建核心執行緒池
        /// <summary>
        /// 創建核心執行緒池
        /// </summary>
        private void CreateCoreThreads(int? coreThreadCount = null)
        {
            if (coreThreadCount != null) _coreThreadCount = coreThreadCount.Value;

            for (int i = 0; i < _coreThreadCount; i++)
            {
                Interlocked.Increment(ref _activeThreadCount);
                Thread thread = null;
                thread = new Thread(new ThreadStart(() =>
                {
                    Task task;
                    while (_run)
                    {
                        if (_tasks.TryDequeue(out task))
                        {
                            TryExecuteTask(task);
                            Interlocked.Decrement(ref _runCount);
                        }
                        else
                        {
                            _sem.WaitOne();
                            Interlocked.Decrement(ref _semCount);
                        }
                    }
                    Interlocked.Decrement(ref _activeThreadCount);
                    if (_activeThreadCount == 0)
                    {
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                        if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                        {
                            SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
                        }
                    }
                }));
                thread.IsBackground = true;
                thread.Start();
            }
        }
        #endregion

        #region 創建輔助執行緒
        /// <summary>
        /// 創建輔助執行緒
        /// </summary>
        private void CreateThread()
        {
            Interlocked.Increment(ref _activeThreadCount);
            Thread thread = null;
            thread = new Thread(new ThreadStart(() =>
            {
                Task task;
                DateTime dt = DateTime.Now;
                while (_run && DateTime.Now.Subtract(dt).TotalMilliseconds < _auxiliaryThreadTimeOut)
                {
                    if (_tasks.TryDequeue(out task))
                    {
                        TryExecuteTask(task);
                        Interlocked.Decrement(ref _runCount);
                        dt = DateTime.Now;
                    }
                    else
                    {
                        _sem.WaitOne(_auxiliaryThreadTimeOut);
                        Interlocked.Decrement(ref _semCount);
                    }
                }
                Interlocked.Decrement(ref _activeThreadCount);
                if (_activeThreadCount == _coreThreadCount)
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                    {
                        SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
                    }
                }
            }));
            thread.IsBackground = true;
            thread.Start();
        }
        #endregion

        #region 全部取消
        /// <summary>
        /// 全部取消
        /// 取消佇列中尚未執行的任務
        /// </summary>
        public void CancelAll()
        {
            Task tempTask;
            while (_tasks.TryDequeue(out tempTask))
            {
                Interlocked.Decrement(ref _runCount);
            }
        }
        #endregion

    }
}
View Code

    TaskSchedulerEx類代碼(使用AutoResetEvent實作):

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Utils
{
    /// <summary>
    /// TaskScheduler擴展
    /// 每個實體都是獨立執行緒池
    /// </summary>
    public class TaskSchedulerEx : TaskScheduler, IDisposable
    {
        #region 外部方法
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
        #endregion

        #region 變數屬性事件
        private ConcurrentQueue<Task> _tasks = new ConcurrentQueue<Task>();
        private int _coreThreadCount = 0;
        private int _maxThreadCount = 0;
        private int _auxiliaryThreadTimeOut = 20000; //輔助執行緒釋放時間
        private int _activeThreadCount = 0;
        private System.Timers.Timer _timer;
        private object _lockCreateTimer = new object();
        private bool _run = true;
        private AutoResetEvent _evt = new AutoResetEvent(false);

        /// <summary>
        /// 活躍執行緒數
        /// </summary>
        public int ActiveThreadCount
        {
            get { return _activeThreadCount; }
        }

        /// <summary>
        /// 核心執行緒數
        /// </summary>
        public int CoreThreadCount
        {
            get { return _coreThreadCount; }
        }

        /// <summary>
        /// 最大執行緒數
        /// </summary>
        public int MaxThreadCount
        {
            get { return _maxThreadCount; }
        }
        #endregion

        #region 建構式
        /// <summary>
        /// TaskScheduler擴展
        /// 每個實體都是獨立執行緒池
        /// </summary>
        /// <param name="coreThreadCount">核心執行緒數(大于或等于0,不宜過大)(如果是一次性使用,則設定為0比較合適)</param>
        /// <param name="maxThreadCount">最大執行緒數</param>
        public TaskSchedulerEx(int coreThreadCount = 10, int maxThreadCount = 20)
        {
            _maxThreadCount = maxThreadCount;
            CreateCoreThreads(coreThreadCount);
        }
        #endregion

        #region override GetScheduledTasks
        protected override IEnumerable<Task> GetScheduledTasks()
        {
            return _tasks;
        }
        #endregion

        #region override TryExecuteTaskInline
        protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
        {
            return false;
        }
        #endregion

        #region override QueueTask
        protected override void QueueTask(Task task)
        {
            CreateTimer();
            _tasks.Enqueue(task);
            _evt.Set();
        }
        #endregion

        #region 資源釋放
        /// <summary>
        /// 資源釋放
        /// 佇列中尚未執行的任務不再執行
        /// </summary>
        public void Dispose()
        {
            _run = false;

            if (_timer != null)
            {
                _timer.Stop();
                _timer.Dispose();
                _timer = null;
            }

            while (_activeThreadCount > 0)
            {
                _evt.Set();
            }
        }
        #endregion

        #region 創建核心執行緒池
        /// <summary>
        /// 創建核心執行緒池
        /// </summary>
        private void CreateCoreThreads(int? coreThreadCount = null)
        {
            if (coreThreadCount != null) _coreThreadCount = coreThreadCount.Value;

            for (int i = 0; i < _coreThreadCount; i++)
            {
                Interlocked.Increment(ref _activeThreadCount);
                Thread thread = null;
                thread = new Thread(new ThreadStart(() =>
                {
                    Task task;
                    while (_run)
                    {
                        if (_tasks.TryDequeue(out task))
                        {
                            TryExecuteTask(task);
                        }
                        else
                        {
                            _evt.WaitOne();
                        }
                    }
                    Interlocked.Decrement(ref _activeThreadCount);
                    if (_activeThreadCount == 0)
                    {
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                        if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                        {
                            SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
                        }
                    }
                }));
                thread.IsBackground = true;
                thread.Start();
            }
        }
        #endregion

        #region 創建輔助執行緒
        /// <summary>
        /// 創建輔助執行緒
        /// </summary>
        private void CreateThread()
        {
            Interlocked.Increment(ref _activeThreadCount);
            Thread thread = null;
            thread = new Thread(new ThreadStart(() =>
            {
                Task task;
                DateTime dt = DateTime.Now;
                while (_run && DateTime.Now.Subtract(dt).TotalMilliseconds < _auxiliaryThreadTimeOut)
                {
                    if (_tasks.TryDequeue(out task))
                    {
                        TryExecuteTask(task);
                        dt = DateTime.Now;
                    }
                    else
                    {
                        _evt.WaitOne(_auxiliaryThreadTimeOut);
                    }
                }
                Interlocked.Decrement(ref _activeThreadCount);
                if (_activeThreadCount == _coreThreadCount)
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                    {
                        SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
                    }
                }
            }));
            thread.IsBackground = true;
            thread.Start();
        }
        #endregion

        #region 創建定時器
        private void CreateTimer()
        {
            if (_timer == null) //_timer不為空時,跳過,不走lock,提升性能
            {
                if (_activeThreadCount >= _coreThreadCount && _activeThreadCount < _maxThreadCount) //活躍執行緒數達到最大執行緒數時,跳過,不走lock,提升性能
                {
                    lock (_lockCreateTimer)
                    {
                        if (_timer == null)
                        {
                            _timer = new System.Timers.Timer();
                            _timer.Interval = _coreThreadCount == 0 ? 1 : 500;
                            _timer.Elapsed += (s, e) =>
                            {
                                if (_activeThreadCount >= _coreThreadCount && _activeThreadCount < _maxThreadCount)
                                {
                                    if (_tasks.Count > 0)
                                    {
                                        if (_timer.Interval != 20) _timer.Interval = 20;
                                        CreateThread();
                                    }
                                    else
                                    {
                                        if (_timer.Interval != 500) _timer.Interval = 500;
                                    }
                                }
                                else
                                {
                                    if (_timer != null)
                                    {
                                        _timer.Stop();
                                        _timer.Dispose();
                                        _timer = null;
                                    }
                                }
                            };
                            _timer.Start();
                        }
                    }
                }
            }
        }
        #endregion

        #region 全部取消
        /// <summary>
        /// 全部取消
        /// 取消佇列中尚未執行的任務
        /// </summary>
        public void CancelAll()
        {
            Task tempTask;
            while (_tasks.TryDequeue(out tempTask)) { }
        }
        #endregion

    }
}
View Code

    RunHelper類代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Utils
{
    /// <summary>
    /// 執行緒工具類
    /// </summary>
    public static class RunHelper
    {
        #region 變數屬性事件

        #endregion

        #region 執行緒中執行
        /// <summary>
        /// 執行緒中執行
        /// </summary>
        public static Task Run(this TaskScheduler scheduler, Action<object> doWork, object arg = null, Action<Exception> errorAction = null)
        {
            return Task.Factory.StartNew((obj) =>
            {
                try
                {
                    doWork(obj);
                }
                catch (Exception ex)
                {
                    if (errorAction != null) errorAction(ex);
                    LogUtil.Error(ex, "ThreadUtil.Run錯誤");
                }
            }, arg, CancellationToken.None, TaskCreationOptions.None, scheduler);
        }
        #endregion

        #region 執行緒中執行
        /// <summary>
        /// 執行緒中執行
        /// </summary>
        public static Task Run(this TaskScheduler scheduler, Action doWork, Action<Exception> errorAction = null)
        {
            return Task.Factory.StartNew(() =>
            {
                try
                {
                    doWork();
                }
                catch (Exception ex)
                {
                    if (errorAction != null) errorAction(ex);
                    LogUtil.Error(ex, "ThreadUtil.Run錯誤");
                }
            }, CancellationToken.None, TaskCreationOptions.None, scheduler);
        }
        #endregion

        #region 執行緒中執行
        /// <summary>
        /// 執行緒中執行
        /// </summary>
        public static Task<T> Run<T>(this TaskScheduler scheduler, Func<object, T> doWork, object arg = null, Action<Exception> errorAction = null)
        {
            return Task.Factory.StartNew<T>((obj) =>
            {
                try
                {
                    return doWork(obj);
                }
                catch (Exception ex)
                {
                    if (errorAction != null) errorAction(ex);
                    LogUtil.Error(ex, "ThreadUtil.Run錯誤");
                    return default(T);
                }
            }, arg, CancellationToken.None, TaskCreationOptions.None, scheduler);
        }
        #endregion

        #region 執行緒中執行
        /// <summary>
        /// 執行緒中執行
        /// </summary>
        public static Task<T> Run<T>(this TaskScheduler scheduler, Func<T> doWork, Action<Exception> errorAction = null)
        {
            return Task.Factory.StartNew<T>(() =>
            {
                try
                {
                    return doWork();
                }
                catch (Exception ex)
                {
                    if (errorAction != null) errorAction(ex);
                    LogUtil.Error(ex, "ThreadUtil.Run錯誤");
                    return default(T);
                }
            }, CancellationToken.None, TaskCreationOptions.None, scheduler);
        }
        #endregion

        #region 執行緒中執行
        /// <summary>
        /// 執行緒中執行
        /// </summary>
        public static async Task<T> RunAsync<T>(this TaskScheduler scheduler, Func<object, T> doWork, object arg = null, Action<Exception> errorAction = null)
        {
            return await Task.Factory.StartNew<T>((obj) =>
            {
                try
                {
                    return doWork(obj);
                }
                catch (Exception ex)
                {
                    if (errorAction != null) errorAction(ex);
                    LogUtil.Error(ex, "ThreadUtil.Run錯誤");
                    return default(T);
                }
            }, arg, CancellationToken.None, TaskCreationOptions.None, scheduler);
        }
        #endregion

        #region 執行緒中執行
        /// <summary>
        /// 執行緒中執行
        /// </summary>
        public static async Task<T> RunAsync<T>(this TaskScheduler scheduler, Func<T> doWork, Action<Exception> errorAction = null)
        {
            return await Task.Factory.StartNew<T>(() =>
            {
                try
                {
                    return doWork();
                }
                catch (Exception ex)
                {
                    if (errorAction != null) errorAction(ex);
                    LogUtil.Error(ex, "ThreadUtil.Run錯誤");
                    return default(T);
                }
            }, CancellationToken.None, TaskCreationOptions.None, scheduler);
        }
        #endregion

    }
}
View Code

    TaskHelper擴展類:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Utils
{
    /// <summary>
    /// Task幫助類基類
    /// </summary>
    public class TaskHelper
    {
        #region 變數
        /// <summary>
        /// 處理器數
        /// </summary>
        private static int _processorCount = Environment.ProcessorCount;
        #endregion

        #region UI任務
        private static TaskScheduler _UITask;
        /// <summary>
        /// UI任務(2-4個執行緒)
        /// </summary>
        public static TaskScheduler UITask
        {
            get
            {
                if (_UITask == null) _UITask = new TaskSchedulerEx(2, 4);
                return _UITask;
            }
        }
        #endregion

        #region 選單任務
        private static TaskScheduler _MenuTask;
        /// <summary>
        /// 選單任務(2-4個執行緒)
        /// </summary>
        public static TaskScheduler MenuTask
        {
            get
            {
                if (_MenuTask == null) _MenuTask = new TaskSchedulerEx(2, 4);
                return _MenuTask;
            }
        }
        #endregion

        #region 計算任務
        private static TaskScheduler _CalcTask;
        /// <summary>
        /// 計算任務(執行緒數:處理器數*2)
        /// </summary>
        public static TaskScheduler CalcTask
        {
            get
            {
                if (_CalcTask == null) _CalcTask = new LimitedTaskScheduler(_processorCount * 2);
                return _CalcTask;
            }
        }
        #endregion

        #region 網路請求
        private static TaskScheduler _RequestTask;
        /// <summary>
        /// 網路請求(8-32個執行緒)
        /// </summary>
        public static TaskScheduler RequestTask
        {
            get
            {
                if (_RequestTask == null) _RequestTask = new TaskSchedulerEx(8, 32);
                return _RequestTask;
            }
        }
        #endregion

        #region 資料庫任務
        private static TaskScheduler _DBTask;
        /// <summary>
        /// 資料庫任務(8-32個執行緒)
        /// </summary>
        public static TaskScheduler DBTask
        {
            get
            {
                if (_DBTask == null) _DBTask = new TaskSchedulerEx(8, 32);
                return _DBTask;
            }
        }
        #endregion

        #region IO任務
        private static TaskScheduler _IOTask;
        /// <summary>
        /// IO任務(8-32個執行緒)
        /// </summary>
        public static TaskScheduler IOTask
        {
            get
            {
                if (_IOTask == null) _IOTask = new TaskSchedulerEx(8, 32);
                return _IOTask;
            }
        }
        #endregion

        #region 首頁任務
        private static TaskScheduler _MainPageTask;
        /// <summary>
        /// 首頁任務(8-32個執行緒)
        /// </summary>
        public static TaskScheduler MainPageTask
        {
            get
            {
                if (_MainPageTask == null) _MainPageTask = new TaskSchedulerEx(8, 32);
                return _MainPageTask;
            }
        }
        #endregion

        #region 圖片加載任務
        private static TaskScheduler _LoadImageTask;
        /// <summary>
        /// 圖片加載任務(8-32個執行緒)
        /// </summary>
        public static TaskScheduler LoadImageTask
        {
            get
            {
                if (_LoadImageTask == null) _LoadImageTask = new TaskSchedulerEx(8, 32);
                return _LoadImageTask;
            }
        }
        #endregion

        #region 瀏覽器任務
        private static TaskScheduler _BrowserTask;
        /// <summary>
        /// 瀏覽器任務(2-4個執行緒)
        /// </summary>
        public static TaskScheduler BrowserTask
        {
            get
            {
                if (_BrowserTask == null) _BrowserTask = new TaskSchedulerEx(2, 4);
                return _BrowserTask;
            }
        }
        #endregion

    }
}
View Code

    Form1.cs測驗代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Utils;

namespace test
{
    public partial class Form1 : Form
    {
        private TaskSchedulerEx _taskSchedulerEx = null;
        private TaskSchedulerEx _taskSchedulerExSmall = null;
        private TaskSchedulerEx _task = null;

        public Form1()
        {
            InitializeComponent();
            _taskSchedulerEx = new TaskSchedulerEx(50, 500);
            _taskSchedulerExSmall = new TaskSchedulerEx(5, 50);
            _task = new TaskSchedulerEx(2, 10);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 模擬大量網路請求任務
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            DoTask(_taskSchedulerEx, 200000, 1000, 20);
        }

        /// <summary>
        /// 模擬CPU密集型任務
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            DoTask(_taskSchedulerEx, 100000, 2000, 1);
        }

        /// <summary>
        /// 模擬大量網路請求任務
        /// </summary>
        private void button3_Click(object sender, EventArgs e)
        {
            DoTask(_taskSchedulerExSmall, 2000, 100, 20);
        }

        /// <summary>
        /// 模擬CPU密集型任務
        /// </summary>
        private void button4_Click(object sender, EventArgs e)
        {
            DoTask(_taskSchedulerExSmall, 2000, 100, 1);
        }

        /// <summary>
        /// 模擬任務
        /// </summary>
        /// <param name="scheduler">scheduler</param>
        /// <param name="taskCount">任務數量</param>
        /// <param name="logCount">每隔多少條資料打一個日志</param>
        /// <param name="delay">模擬延遲或耗時(毫秒)</param>
        private void DoTask(TaskSchedulerEx scheduler, int taskCount, int logCount, int delay)
        {
            _task.Run(() =>
            {
                Log("開始");
                DateTime dt = DateTime.Now;
                List<Task> taskList = new List<Task>();
                for (int i = 1; i <= taskCount; i++)
                {
                    Task task = scheduler.Run((obj) =>
                    {
                        var k = (int)obj;
                        Thread.Sleep(delay); //模擬延遲或耗時
                        if (k % logCount == 0)
                        {
                            Log("最大執行緒數:" + scheduler.MaxThreadCount + " 核心執行緒數:" + scheduler.CoreThreadCount + " 活躍執行緒數:" + scheduler.ActiveThreadCount.ToString().PadLeft(4, ' ') + " 處理數/總數:" + k + " / " + taskCount);
                        }
                    }, i, (ex) =>
                    {
                        Log(ex.Message);
                    });
                    taskList.Add(task);
                }
                Task.WaitAll(taskList.ToArray());
                double d = DateTime.Now.Subtract(dt).TotalSeconds;
                Log("完成,耗時:" + d + "");
            });
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_taskSchedulerEx != null)
            {
                _taskSchedulerEx.Dispose(); //釋放資源
                _taskSchedulerEx = null;
            }
        }
    }
}
View Code

     測驗截圖:

 

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/24018.html

標籤:C#

上一篇:震驚!Windows Service服務和定時任務框架quartz之間原來是這種關系……

下一篇:C#基于NModbus實作MODBUSTCP字串、浮點數讀寫

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more