LimitedConcurrencyLevelTaskScheduler
//--------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// File: LimitedConcurrencyTaskScheduler.cs
//
//-------------------------------------------------------------------------- using System.Collections.Generic;
using System.Linq; namespace System.Threading.Tasks.Schedulers
{
/// <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 = ; // 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 < ) 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 == )
{
--_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);
}
}
}
}
LimitedConcurrencyLevelTaskScheduler的更多相关文章
- 关于 LimitedConcurrencyLevelTaskScheduler 的疑惑
1. LimitedConcurrencyLevelTaskScheduler 介绍 这个TaskScheduler用过的应该都知道,微软开源的一个任务调度器,它的代码很简单, 也很好懂,但是我没有明 ...
- C#任务调度——LimitedConcurrencyLevelTaskScheduler
这是参考大佬分享的代码写的有问题请提出指正,谢谢. using Serilog; using System; using System.Collections.Generic; using Syste ...
- c#与java的区别
经常有人问这种问题,用了些时间java之后,发现这俩玩意除了一小部分壳子长的还有能稍微凑合上,基本上没什么相似之处,可以说也就是马甲层面上的相似吧,还是比较短的马甲... 一般C#多用于业务系统的开发 ...
- ENode 2.0 - 介绍一下关于ENode中对Command的调度设计
CQRS架构,C端的职责是处理从上层发送过来的command.对于单台机器来说,我们如何尽快的处理command呢?本文想通过不断提问和回答的方式,把我的思考写出来. 首先,我们最容易想到的是使用多线 ...
- task 限制任务数量(转自msdn)
public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler { // Indicates whether the current ...
- 怎么设置task的最大线程数
//-------------------------------------------------------------------------- // // Copyright (c) Mic ...
- Asp.Net任务Task和线程Thread
Task是.NET4.0加入的,跟线程池ThreadPool的功能类似,用Task开启新任务时,会从线程池中调用线程,而Thread每次实例化都会创建一个新的线程.任务(Task)是架构在线程之上的, ...
- TaskFactory设置并发量
Task对象很多人知道了(使用Task代替ThreadPool和Thread, C#线程篇—Task(任务)和线程池不得不说的秘密(5)) 相对的还有TaskScheduler 这个调度器,可以自定义 ...
随机推荐
- 可变对象(immutable)和不可变对象(mutable)
可变对象(immutable)和不可变对象(mutable) 这个是之前一直忽略的一个知识点,比方说说起String为什么是一个不可变对象,只知道因为它是被final修饰的所以不可变,而没有抓住不可变 ...
- 在WAS控制台,环境下添加新的虚拟主机别名
错误现象: 11/16/13 16:52:22:612 CST] 00000021 util W com.ibm.ws.webcontainer.util.VirtualHostCo ...
- BIND简易教程(0):在Ubuntu下源码安装BIND(其实跟前面的教程没太大关系)
之前介绍过BIND的基本使用啦.关于BIND的入门级使用方法见:http://www.cnblogs.com/anpengapple/p/5877661.html简易教程系列,本篇只讲BIND安装. ...
- HDU 5724 Chess(SG函数)
Chess Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submi ...
- Coursera机器学习基石 第2讲:感知器
第一讲中我们学习了一个机器学习系统的完整框架,包含以下3部分:训练集.假设集.学习算法 一个机器学习系统的工作原理是:学习算法根据训练集,从假设集合H中选择一个最好的假设g,使得g与目标函数f尽可能低 ...
- 二十六、关于 IntelliJ IDEA 中 Schedule for Addition 的问题
在我们使用 IntelliJ IDEA 的时候,经常会遇到这种情况,即: 从 SVN 检出项目之后,并用 IDEA 首次打开项目,IDEA 会弹出如下选择框: 如上图所示,让我们选择是否将XXX.im ...
- java根据数据库自动生成代码
出现这个已经创建成功 出现这个情况,没有使用DBUtil,引入即可 已经创建完成 代码下载:https://github.com/weibanggang/tool 项目实例下载:https://pan ...
- 第21章 DMA—直接存储区访问
本章参考资料:<STM32F76xxx参考手册>DMA控制器章节. 学习本章时,配合<STM32F76xxx参考手册>DMA控制器章节一起阅读,效果会更佳,特别是涉及到寄存器说 ...
- wordpress上传含中文文件名出现乱码
一.首先到FTP里面找到wp-admin/includes/file.php这个文件. 二.查找wp_handle_upload在文件里面找到以下代码. function wp_handle_uplo ...
- Flex布局(一)flex-direction
采用Flex布局的元素,被称为Flex容器(flex container),简称"容器".其所有子元素自动成为容器成员,成为Flex项目(Flex item),简称"项目 ...