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 这个调度器,可以自定义 ...
随机推荐
- (第二场)A Run 【动态规划】
链接:https://www.nowcoder.com/acm/contest/140/A 题目描述: White Cloud is exercising in the playground.Whit ...
- 如何安装zip格式的MySQL
1.MySQL安装文件分为两种,一种是msi格式的,一种是zip格式的.如果是msi格式的可以直接点击安装,按照它给出的安装提示进行安装(相信大家的英文可以看懂英文提示),一般MySQL将会安装在C: ...
- EF Core 2.0中Transaction事务会对DbContext底层创建和关闭数据库连接的行为有所影响
数据库 我们先在SQL Server数据库中建立一个Book表: CREATE TABLE [dbo].[Book]( ,) NOT NULL, ) NULL, ) NULL, ) NULL, [Cr ...
- 安全过滤javascript,html,防止跨脚本攻击
本文改自: http://blog.51yip.com/php/1031.html 用户输入的东西是不可信认的,例如,用户注册,用户评论等,这样的数据,你不光要做好防sql的注入,还要防止JS的注入, ...
- ConfigurationManager.AppSettings方法
一 配置文件概述: 应用程序配置文件是标准的 XML 文件,XML 标记和属性是区分大小写的.它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序.配置文件的根节点是conf ...
- 汇编中PSP是什么?为什么一般cs比ds大10h
一般来说,PSP是256个字节,当程度生成了可执行文件以后,在执行的时候,先将程序调入内存, 这个时候DS中存入程序在内存中的段地址,紧接着是程序的一些说明,比如说程序占用多大空间等 等,这就是PSP ...
- c++基础STL
今天给大家介绍几个容器,包含的头文件为<vector>,<stack>,<queue>,<map>,<list>,<deque> ...
- 『ACM C++』 Codeforces | 1003C - Intense Heat
今日兴趣新闻: NASA 研制最强推进器,加速度可达每秒 40 公里,飞火星全靠它 链接:https://mbd.baidu.com/newspage/data/landingsuper?contex ...
- mqtt使用一
最近做的一个项目用到了mqtt协议,我需要从第三方订阅主题接受消息,还需要自己搭建,mqtt服务器去发布主题.下面就详细介绍一下环境的搭建和使用. 1.mqtt介绍 MQTT是一个基于客户端-服务器的 ...
- Java中常见的比较
一.StringBuffer.StringBuilder.String 1) 都是 final 类, 都不允许被继承; 2) String 长度是不可变的, StringBuffer.StringBu ...