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.mzph.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 的任一支持设备搭配使用…