C#任務調度——LimitedConcurrencyLevelTaskScheduler

  • 這是參考大佬分享的代碼寫的有問題請提出指正,謝謝。
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;namespace TaskManager
{class TaskFactoryMananger{//USEpublic static void Run(){try{while (true){LimitedConcurrencyLevelTaskScheduler lcts = new LimitedConcurrencyLevelTaskScheduler(10);TaskFactory factory = new TaskFactory(lcts);Task[] spiderTask = new Task[] {factory.StartNew(() =>{Log.Logger.Information("{0} Start on thread {1}", "111", Thread.CurrentThread.ManagedThreadId);     Log.Logger.Information("{0} Finish  on thread {1}", "111", Thread.CurrentThread.ManagedThreadId);}),factory.StartNew(() =>{Thread.Sleep(TimeSpan.FromSeconds(3));Log.Logger.Information("{0} Start on thread {1}", "222", Thread.CurrentThread.ManagedThreadId);Log.Logger.Information("{0} Finish  on thread {1}", "222", Thread.CurrentThread.ManagedThreadId);}),factory.StartNew(() =>{Thread.Sleep(TimeSpan.FromSeconds(5));Log.Logger.Information("{0} Start on thread {1}", "333", Thread.CurrentThread.ManagedThreadId);Log.Logger.Information("{0} Finish  on thread {1}", "333", Thread.CurrentThread.ManagedThreadId);})};Task.WaitAll(spiderTask);Thread.Sleep(TimeSpan.FromMinutes(1));}}catch (AggregateException ex){foreach (Exception inner in ex.InnerExceptions){Log.Logger.Error(inner.Message);}}}/// <summary>/// Provides a task scheduler that ensures a maximum concurrency level while/// running on top of the ThreadPool./// </summary>public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler{/// <summary>Whether the current thread is processing work items.</summary>[ThreadStatic]private static bool _currentThreadIsProcessingItems;/// <summary>The list of tasks to be executed.</summary>private readonly LinkedList<Task> _tasks = new LinkedList<Task>(); // protected by lock(_tasks)/// <summary>The maximum concurrency level allowed by this scheduler.</summary>private readonly int _maxDegreeOfParallelism;/// <summary>Whether the scheduler is currently processing work items.</summary>private int _delegatesQueuedOrRunning = 0; // protected by lock(_tasks)/// <summary>/// Initializes an instance of the LimitedConcurrencyLevelTaskScheduler class with the/// specified degree of parallelism./// </summary>/// <param name="maxDegreeOfParallelism">The maximum degree of parallelism provided by this scheduler.</param>public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism){if (maxDegreeOfParallelism < 1) throw new ArgumentOutOfRangeException("maxDegreeOfParallelism");_maxDegreeOfParallelism = maxDegreeOfParallelism;}/// <summary>Queues a task to the scheduler.</summary>/// <param name="task">The task to be queued.</param>protected sealed override void QueueTask(Task task){// Add the task to the list of tasks to be processed.  If there aren't enough// delegates currently queued or running to process tasks, schedule another.lock (_tasks){_tasks.AddLast(task);if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism){++_delegatesQueuedOrRunning;NotifyThreadPoolOfPendingWork();}}}/// <summary>/// Informs the ThreadPool that there's work to be executed for this scheduler./// </summary>private void NotifyThreadPoolOfPendingWork(){ThreadPool.UnsafeQueueUserWorkItem(_ =>{// Note that the current thread is now processing work items.// This is necessary to enable inlining of tasks into this thread._currentThreadIsProcessingItems = true;try{// Process all available items in the queue.while (true){Task item;lock (_tasks){// When there are no more items to be processed,// note that we're done processing, and get out.if (_tasks.Count == 0){--_delegatesQueuedOrRunning;break;}// Get the next item from the queueitem = _tasks.First.Value;_tasks.RemoveFirst();}// Execute the task we pulled out of the queuebase.TryExecuteTask(item);}}// We're done processing items on the current threadfinally { _currentThreadIsProcessingItems = false; }}, null);}/// <summary>Attempts to execute the specified task on the current thread.</summary>/// <param name="task">The task to be executed.</param>/// <param name="taskWasPreviouslyQueued"></param>/// <returns>Whether the task could be executed on the current thread.</returns>protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued){// If this thread isn't already processing a task, we don't support inliningif (!_currentThreadIsProcessingItems) return false;// If the task was previously queued, remove it from the queueif (taskWasPreviouslyQueued) TryDequeue(task);// Try to run the task.return base.TryExecuteTask(task);}/// <summary>Attempts to remove a previously scheduled task from the scheduler.</summary>/// <param name="task">The task to be removed.</param>/// <returns>Whether the task could be found and removed.</returns>protected sealed override bool TryDequeue(Task task){lock (_tasks) return _tasks.Remove(task);}/// <summary>Gets the maximum concurrency level supported by this scheduler.</summary>public sealed override int MaximumConcurrencyLevel { get { return _maxDegreeOfParallelism; } }/// <summary>Gets an enumerable of the tasks currently scheduled on this scheduler.</summary>/// <returns>An enumerable of the tasks currently scheduled.</returns>protected sealed override IEnumerable<Task> GetScheduledTasks(){bool lockTaken = false;try{Monitor.TryEnter(_tasks, ref lockTaken);if (lockTaken) return _tasks.ToArray();else throw new NotSupportedException();}finally{if (lockTaken) Monitor.Exit(_tasks);}}}}
}

轉載于:https://www.cnblogs.com/TTonly/p/10349916.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/449997.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/449997.shtml
英文地址,請注明出處:http://en.pswp.cn/news/449997.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

同步本地遠程分支 git remote prune origin

git remote prune origin &#xff08;不常用總忘記&#xff0c;記錄下&#xff09;

264 參考幀 list0 list1

作了這么久的h264工作&#xff0c;這部分還一直從未去深入了解過&#xff0c;真是不求甚解啊&#xff0c;那幫老外的代碼也寫得太全了&#xff0c;該部分至今天才開始研究 首先參考幀這里關注的是兩種&#xff0c;p ,b ,前向參考和后向參考 由白皮書中看到&#xff0c;p幀的參…

面試官問我:什么是JavaScript閉包,我該如何回答

閉包&#xff0c;有人說它是一種設計理念&#xff0c;有人說所有的函數都是閉包。到底什么是閉包&#xff1f;這個問題在面試是時候經常都會被問&#xff0c;很多小白一聽就懵逼了&#xff0c;不知道如何回答好。這個問題也有很多朋友在公眾號給李老師留言了&#xff0c;問題表…

robotframework基礎學習(8)

變量的使用 在 Edit 標簽頁中主要分&#xff1a;加載外部文件、定義內部變量、定義元數據等三個部分。 &#xff08;1&#xff09;&#xff1a;加載外部文件Add Library&#xff1a;加載測試庫&#xff0c;主要是[PYTHON 目錄]\Lib\site-packages 里的測試庫 Add Resource&…

版本字符串比較工具接口常用接口函數

版本升級比較常用的接口&#xff0c;字符串解析&#xff0c;不是很難&#xff0c;但沒必須重復造輪子&#xff0c;保存一份網上搜到的實現&#xff1a; /*** 比較版本號的大小,前者大則返回一個正數,后者大返回一個負數,相等則返回0** param version1* param version2* return…

[藍橋杯]ALGO-188.算法訓練_P0504

Anagrams指的是具有如下特性的兩個單詞&#xff1a;在這兩個單詞當中&#xff0c;每一個英文字母&#xff08;不區分大小寫&#xff09;所出現的次數都是相同的。例如&#xff0c;Unclear和Nuclear、Rimon和MinOR都是Anagrams。編寫一個程序&#xff0c;輸入兩個單詞&#xff0…

什么是3-2混合

正如上面所述&#xff0c;電影轉換成視頻時&#xff0c;每秒24幀必須轉成每秒60場&#xff08;30幀&#xff09;。實現這一點的方法是把電影的第一幀顯示3場&#xff0c;然后把第二幀顯示2場&#xff0c;再把第三幀顯示3場&#xff0c;以此類推。這個3-2-3-2-3-2的順序就被稱為…

shell 的here document 用法、輸入/輸出重定向

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 什么是Here Document Here Document 是在Linux Shell 中的一種特殊的重定向方式&#xff0c;它的基本的形式如下 cmd << delimiter…

beta第二天

團隊成員 鄭西坤 031602542 &#xff08;隊長&#xff09; 陳俊杰 031602504陳順興 031602505張勝男 031602540廖鈺萍 031602323雷光游 031602319吳志鴻 0316206341.昨天的困難 陳順興&#xff1a;無 廖鈺萍&#xff1a;無 吳志鴻&#xff1a;沒有 雷光游&#xff1a;無 鄭西坤…

void和void *

void f(void) { // 參數void可以省略cout << "aa"<<endl; } int t 22; int *a &t; void *p; // void *可以被賦值為其他類型 p a; cout << *(int *)p; // 使用的時候必須轉到那個類型 轉載于:https://www.cnblogs.com/pjishu/p/10343587.…

Android應用開發—Application

What is Application Application和Activity&#xff0c;Service一樣是android框架的一個系統組件&#xff0c;當android程序啟動時系統會創建一個application對象&#xff0c;用來存儲系統的一些信息。通常我們是不需要指定一個Application的&#xff0c;這時系統會自動幫我們…

C語言符號

C語言運算符的優先級 一、運算符的優先級表 C 語言的符號眾多&#xff0c;由這些符號又組合成了各種各樣的運算符。既然是運算符就一定有其特定的優先級&#xff0c;下表就是C 語言運算符的優先級表&#xff1a; 注&#xff1a;同一優先級的運算符&#xff0c;運算次序由結合…

手機按鍵中控運行思路的個人理解

目前而言基本的自己理解的中控多線程腳本無非就是兩種1.主代碼作為腳本功能的載體 另外開辟一個線程作為和中控保持聯系的部分(下面只是思路 無法直接運行)Import "zm.luae" zm.Init /* 該思路下的基本流程 從UI界面獲取到云賬號 和 本地的配置信息---->根據自己…

burp過期了,換一個

先從吾愛破解論壇下載工具&#xff1a;https://down.52pojie.cn/Tools/Network_Analyzer/Burp_Suite_Pro_v1.7.37_Loader_Keygen.zip 工具運行需要Java環境&#xff0c;請自行安裝&#xff0c;此處不贅述。解壓完后雙擊keygen 填一下License Text(隨意)&#xff0c;然后點擊Run…

加載一張圖片到ImageView到底占據多少內存

https://blog.csdn.net/BUG_delete/article/details/79557939 簡介 Android中經常要通過ImageView進行圖片資源顯示。在加載圖片時&#xff0c;首先要考慮的兩個因素就是體驗問題和性能問題。 其中&#xff0c;體驗問題是指圖片顯示的是否正確&#xff08;例如Universal-Imag…

mysql -u root -p 解釋

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 mysql -u 用戶名 -p 密碼 是連接數據庫服務器的命令。要求你輸入自己連接數據庫的用戶名和密碼。 考慮密碼如果直接明文寫在這條命令行…

hbase 概念

在hbase里面有幾個通俗的名稱會經常出現 1&#xff09;Hregion region 2&#xff09;Hregionserver regionserver 3&#xff09;Hmaster master 4&#xff09;Hmamstore memstore 5&#xff09;Hfile storeFile 1、什么是hbase&#xff1f; 1&#xff09;它是基于稀疏的、…

beta沖刺第三天

團隊成員 鄭西坤 031602542 &#xff08;隊長&#xff09; 陳俊杰 031602504陳順興 031602505張勝男 031602540廖鈺萍 031602323雷光游 031602319吳志鴻 0316206341.昨天的困難 陳順興&#xff1a;理解別人的代碼 廖鈺萍&#xff1a; 吳志鴻&#xff1a;無 雷光游&#xff1a; …

多線程詳解

1. 進程與線程有那些區別和聯系&#xff1f;   每個進程至少需要一個線程。 進程由兩部分構成&#xff1a;進程內核對象&#xff0c;地址空間。線程也由兩部分組成&#xff1a;線程內核對象&#xff0c;操作系統用它來對線程實施管理。線程堆棧&#xff0c;用于維…

AirPods的自動連接配對原理

首次連接 打開裝有 AirPods 的充電盒&#xff0c;并將它放在 iPhone 旁邊。此時你的 iPhone 上將出現設置動畫。輕點「連接」&#xff0c;然后輕點「完成」。 就這么簡單&#xff0c;而且會自動設置&#xff0c;實現與已使用同一 Apple ID 登錄 iCloud 的任一支持設備搭配使用…