• 这是参考大佬分享的代码写的有问题请提出指正,谢谢。
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

C#任务调度——LimitedConcurrencyLevelTaskScheduler相关推荐

  1. Java基于Quartz的定时任务调度服务(一)

    Quartz的基本用法 一 Quartz的简单介绍 Quartz 是 OpenSymphony 开源组织在任务调度领域的一个开源项目,完全基于 Java 实现,一个优秀的开源调度框架,其特点是:强大的 ...

  2. abaqus高性能服务器怎么用,高性能计算平台ABAQUS任务调度使用说明作者陈林E-Mailchenlin.PDF...

    高性能计算平台ABAQUS任务调度使用说明作者陈林E-Mailchenlin.PDF 高性能计算平台ABAQUS 任务调度使用说明 作者:陈林 E-Mail:chenlin@ 日期:2017-1-10 ...

  3. java timer.schedule如何控制执行次数_Java 分布式任务调度平台:PowerJob 快速开始+配置详解...

    本文适合有 Java 基础知识的人群 作者:HelloGitHub-Salieri 引言 HelloGitHub 推出的<讲解开源项目>[1]系列. 项目地址: https://githu ...

  4. 项目ITP(五) spring4.0 整合 Quartz 实现任务调度

    2014-05-16 22:51 by Jeff Li 前言 系列文章:[传送门] 项目需求: 二维码推送到一体机上,给学生签到扫描用. 然后须要的是 上课前20分钟 .幸好在帮带我的学长做 p2p ...

  5. 几种任务调度的 Java 实现方法与比较

    综观目前的 Web 应用,多数应用都具备任务调度的功能.本文由浅入深介绍了几种任务调度的 Java 实现方法,包括 Timer,Scheduler, Quartz 以及 JCron Tab,并对其优缺 ...

  6. 分布式定时任务调度系统技术选型

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 来源:EFbiz blog.csdn.net/guyue35/ar ...

  7. Spring集成任务调度功能

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试资料 作者:静默虚空 https://github.com/dunwu/ ...

  8. 分布式任务调度系统V1

    分布式任务调度系统V1目标 初步目标实现,实现任务的下发分配,分布式任务执行,支持任务分片(在代码上支持),任务执行记录. 任务调度系统构思 基于C/S架构实现,基于长连接来管理实现,当前版本的逻辑架 ...

  9. 深入分析Spark任务调度的原理--Java后端同学入门Spark编程系列

    作者:陌北有棵树,Java人,架构师社区合伙人! 之前写了一篇:<我作为Java后端,分享一下入门Spark编程的经历!> 上篇是Spark入门的第一篇,写了一些关于Spark编程中RDD ...

最新文章

  1. ipython换行操作_ipython 换行
  2. JVM中GC小对象配置
  3. 详解python 3下文本文件的编解码
  4. 微软进一步融合 Linux,VS Code 官方支持树莓派
  5. 查询mysql所有表的大小
  6. php 输出tab_php实现读取和写入tab分割的文件
  7. 处理顶点——通过切线空间的凹凸映射添加逐像素细节
  8. Spring异步切面源码解析
  9. IOS CA服务器和客户端的配置
  10. java鼠标点击按钮_Java 模拟鼠标事件 java中控制鼠标点击的方法
  11. 如何阻止手机虚拟键盘弹起
  12. 【CVPR 2021】Unsupervised Multi-Source Domain Adaptation for Person Re-Identification (UMSDA)
  13. 上海市犬伤处置门诊目录(上海哪些医院可以打狂犬疫苗)
  14. 操作系统期末知识点浓缩总结复习
  15. 很抱歉,你不涨工资,正是因为你“太努力”!
  16. 只需8步,轻松构建用户画像标签体系
  17. 【opencv小案例-对象提取】阈值分割+形态学处理+面积横纵比过滤
  18. pytorch中的BatchNorm和LayerNorm
  19. 关于spoolsv.exe 报错,并打印服务停止的问题
  20. 计算机组成原理 第三章存储系统 知识点

热门文章

  1. 华为双系统是鸿蒙系统吗,华为p50pro是鸿蒙系统吗-华为p50pro有双系统吗
  2. CCIE-LAB-第七篇-IPV6 EIRGP+Passive
  3. 【Python学习】win10+Anaconda3环境,安装phthon第三方库Jieba
  4. 【动态规划模型】金矿模型理解动态规划!(精彩的故事)
  5. 【HDU - 4990】 Reading comprehension (构造+矩阵快速幂)
  6. 函授本科统考计算机考试时间,函授2006级计算机、机电本科第一学期考试时间安排.doc...
  7. php v9 如何获取超级管理员权限,phpcms v9 增加后台管理员其他权限角色可以查看信息不能修改信息...
  8. Python更改数据类型——astype()方法和to_numeric()函数
  9. leetcode1085. 最小元素各数位之和 py不止是字符串的神!
  10. leetcode72 编辑距离