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

    DataFram类型的变量a,设a有n个样本,m个特征,当执行语句b = a.values后,b为(n, m)的ndarray矩阵类型,当执行c = b.ravel()后,c为(n*m,)维行向量

  2. RSA加密 抛异常 algid parse error, not a sequence

    JDK1.8环境 参考:BouncyCastle的使用:https://blog.csdn.net/qq_29583513/article/details/78866461 可解决 公钥解密 私钥加密 ...

  3. springMvc中获取通过注解获取properties配置文件(转)

    springMvc的项目中,通过注解@Value获取properties配置文件中的配置,使用该注解必须引入的包: spring-beans-4.1.4.RELEASE.jar 下面是需要在sprin ...

  4. SQL中前置0和后置0的处理问题

    在sql语句中经常遇到处理前置和后置数据的问题 1.首先使用convert转化函数对预处理的数据进行转化,CONVERT()函数可以将制定的数据类型转换为另一种数据类型 MySQL 的CAST()和C ...

  5. MySQL_基础

    ## 数据库的基本概念 1. 数据库的英文单词: DataBase 简称 : DB 2. 什么数据库? * 用于存储和管理数据的仓库. 3. 数据库的特点: 1. 持久化存储数据的.其实数据库就是一个 ...

  6. P1880石子合并

    1995年的noi区间dp题,这道题AC耗时达到了数月. 有一道题叫做果子合并,也是求合并的最小花费,但是那个题是可以随便合并两堆,但是这个题只能合并相邻的两堆,并且是一个环.对于环的问题,我们一般可 ...

  7. javaweb:Response/Request的概述 (转发、重定向、get/post)转

    请求响应流程图 1]response 1   response概述 response是Servlet.service方法的一个参数,类型为javax.servlet.http.HttpServletR ...

  8. dict 小习题

    1.请将列表中的每个元素通过 "" 链接起来. users = ['大黑哥','龚明阳',666,'渣渣辉'] a='' for i in users: i=str(i) a=a+ ...

  9. sql server 平方根函数SQRT(x)

    --SQRT(x)返回非负数x的二次方根 示例:select  SQRT(9), SQRT(36); 结果:3    6

  10. 【原创】Themida 2260 虚拟机 FISH 初探(一)

    标 题: [原创]Themida 2260 虚拟机 FISH 初探(一)作 者: xiaohang时 间: 2016-03-03,00:39:37链 接: http://bbs.pediy.com/s ...