• 这是参考大佬分享的代码写的有问题请提出指正,谢谢。
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
{
//USE
public 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 queue
item = _tasks.First.Value;
_tasks.RemoveFirst();
} // Execute the task we pulled out of the queue
base.TryExecuteTask(item);
}
}
// We're done processing items on the current thread
finally { _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 inlining
if (!_currentThreadIsProcessingItems) return false; // If the task was previously queued, remove it from the queue
if (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);
}
}
}
}
}

C#任务调度——LimitedConcurrencyLevelTaskScheduler的更多相关文章

  1. 关于 LimitedConcurrencyLevelTaskScheduler 的疑惑

    1. LimitedConcurrencyLevelTaskScheduler 介绍 这个TaskScheduler用过的应该都知道,微软开源的一个任务调度器,它的代码很简单, 也很好懂,但是我没有明 ...

  2. .net 分布式架构之任务调度平台

    开源地址:http://git.oschina.net/chejiangyi/Dyd.BaseService.TaskManager .net 任务调度平台 用于.net dll,exe的任务的挂载, ...

  3. 免费开源的DotNet任务调度组件Quartz.NET(.NET组件介绍之五)

    很多的软件项目中都会使用到定时任务.定时轮询数据库同步,定时邮件通知等功能..NET Framework具有“内置”定时器功能,通过System.Timers.Timer类.在使用Timer类需要面对 ...

  4. Spring Quartz实现任务调度

    任务调度 在企业级应用中,经常会制定一些"计划任务",即在某个时间点做某件事情 核心是以时间为关注点,即在一个特定的时间点,系统执行指定的一个操作 任务调度涉及多线程并发.线程池维 ...

  5. Quartz实现任务调度

    一.任务调度概述 在企业级应用中,经常会制定一些"计划任务",即在某个时间点做某件事情,核心是以时间为关注点,即在一个特定的时间点,系统执行指定的一个操作,任务调度涉及多线程并发. ...

  6. 基于ASP.NET MVC(C#)和Quartz.Net组件实现的定时执行任务调度

    http://www.cnblogs.com/bobositlife/p/aspnet-mvc-csharp-quartz-net-timer-task-scheduler.html 在之前的文章&l ...

  7. Quartz任务调度基本使用

    转自:http://www.cnblogs.com/bingoidea/archive/2009/08/05/1539656.html 上一篇:定时器的实现.Java定时器Timer和Quartz介绍 ...

  8. 从零开始学 Java - Spring 使用 Quartz 任务调度定时器

    生活的味道 睁开眼看一看窗外的阳光,伸一个懒腰,拿起放在床一旁的水白开水,甜甜的味道,晃着尾巴东张西望的猫猫,在窗台上舞蹈.你向生活微笑,生活也向你微笑. 请你不要询问我的未来,这有些可笑.你问我你是 ...

  9. #研发中间件介绍#定时任务调度与管理JobCenter

    郑昀 最后更新于2014/11/11 关键词:定时任务.调度.监控报警.Job.crontab.Java 本文档适用人员:研发员工   没有JobCenter时我们要面对的:   电商业务链条很长,业 ...

随机推荐

  1. js中的break,continue和return的用法及区别

    为什么要说个?好像很简单,但是我也会迷糊,不懂有时候为什么要用return,然而break和continue也经常和他放在一起. 所以就一起来说一说,这三个看起来很简单,却常常会出错的关键词的具体用法 ...

  2. Scratch少儿编程系列:(十)系列总结及后续计划

    一.系列文章的来由 本篇为该系列文章的一个简单总结, 从初次接触Scratch开始,在写本系列文章过程中,一边读书,一边通过例子做练习. 技术实现,对于我跟人来说,没有什么难度. 我相信,对于一个初次 ...

  3. 应用安全 - Java - 插件 - IO - excel-streaming-reader - 漏洞汇总

    xlsx-streamer.jar的XXE漏洞 Date 类型XXE 影响范围 xlsx-streamer.jar-2.0.0及以下版本 复现

  4. USACO1.6 Superprime Rib

    题目传送门 每一个特殊质数都会被从右边切掉,所以除了首位外的其它位数一定都不会是偶数,只能是$1$,$3$,$5$,$7$,$9$ 而每一个特殊质数的首位一定是质数,也就是$2$,$3$,$5$,$7 ...

  5. 【VS开发】 自己编写一个简单的ActiveX控件——详尽教程

    最近开始学ActiveX控件编程,上手不太容易,上网想找相关教程也没合适的,最后还是在师哥的指导下完成了第一个简单控件的开发,现在把开发过程贴出来与大家分享一下~ (环境说明--平台:vs2005:语 ...

  6. Redis配置主从时报错“Could not connect to Redis at 192.168.0.50:6379: Connection refused not connected>”

    配置Redis主从时,修改完从节点配置文件,然后报错 [root@Rich七哥-0-50 redis]# /opt/redis/redis-cli -h 192.168.0.50 Could not ...

  7. Python3.7 下安装pyqt5

    第一步:首先进入python安装目录下的 [scripts]. 第二步:执行安装pyqt5的命令:python37 -m pip install pyqt5 出现以下安装过程代表安装成功. 第三步:在 ...

  8. [HAOI2018]苹果树题解

    题目链接 大意:不解释 思路: 首先方案数共有n!种,第1个点只有1种选择,第2个点2种选择,生成2个选择的同时消耗一个,第3个点则有3种选择,依次类推共有n!种方案,由于最后答案*n!,故输出的实际 ...

  9. Linux的环境变量.bash_profile .bashrc profile文件

    Shell变量有局部变量.环境变量之分.局部变量就是指在某个Shell中生效的变量,只在此次登录中有效.环境变量通常又称“全局变量”,虽然在Shell中变量默认就是全局的,但是为了让子Shall继承当 ...

  10. SpringMVC-JSON数据交换

    在上Springmvc-JSON数据交换的时候,老师提出了两个问题: 1.JSON数据交互两个注解的作用? 2.静态资源访问的几种配置方式,并简述? 老师刚提出这两个问题的时候我一头雾水的.JSON数 ...