1. LimitedConcurrencyLevelTaskScheduler 介绍

这个TaskScheduler用过的应该都知道,微软开源的一个任务调度器,它的代码很简单,
也很好懂,但是我没有明白的是他是如何实现限制并发数的
首先贴下它的代码,大家先熟悉一下。

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>
/// current executing number;
/// </summary>
public int CurrentCount { get; set; } /// <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)
{
Console.WriteLine("Task Count : {0} ", _tasks.Count);
_tasks.AddLast(task);
if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism)
{
++_delegatesQueuedOrRunning;
NotifyThreadPoolOfPendingWork();
}
}
}
int executingCount = 0;
private static object executeLock = new object();
/// <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);
}
}
}

简单使用

下面是调用代码。

static void Main(string[] args)
{ TaskFactory fac = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(5)); //TaskFactory fac = new TaskFactory();
for (int i = 0; i < 1000; i++)
{ fac.StartNew(s => {
Thread.Sleep(1000);
Console.WriteLine("Current Index {0}, ThreadId {1}",s,Thread.CurrentThread.ManagedThreadId);
}, i);
} Console.ReadKey();
}

调用很简单

根据调试调用顺序可以知道。

使用 LimitedConcurrencyLevelTaskScheduler 创建好TaskFactory 后,

调用该TaskFacotry.StartNew 方法后。会进入 LimitedConcurrencyLevelTaskScheduler

QueueTask 方法。

/// <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)
{
Console.WriteLine("Task Count : {0} ", _tasks.Count);
_tasks.AddLast(task);
if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism)
{
++_delegatesQueuedOrRunning;
NotifyThreadPoolOfPendingWork();
}
}
}

代码很简单,把刚创建的Task 添加到任务队列中去,然后判断当前正在执行的任务数量与设置的允许最大并发数进行比较, 如果小于该值,则开始通知正在挂起的任务开始执行。

我的疑问主要在 NotifyThreadPoolOfPendingWork 这个方法上。

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);
}

从代码中看到的意思是一直跑一个死循环, 不断从_tasks 中取出Task执行,

直到_task为空为止,然后退出循环。从这里并没有看到限制并发数的限制,只有在QueueTask中调用的时候有个简单的限制,然而好像并没有什么卵用,

因为只要 NotifyThreadPoolOfPendingWork 方法启动了, 就会一直跑,直到所有的Task执行完成。那他的并发数是如何限制的呢?

一直很迷惑,是不是我哪里理解错了, 还请知道的大神解惑一下。

~~简直醉了。markdown 不太会用,显示有些问题。。

如果看着不舒服可以看这里 https://www.zybuluo.com/kevinsforever/note/115066

使用这里的编辑器写的,但是复制过来不能正常显示。。

3Q .

关于 LimitedConcurrencyLevelTaskScheduler 的疑惑的更多相关文章

  1. Atitit 图像处理的心得与疑惑 attilax总结

    Atitit 图像处理的心得与疑惑 attilax总结 1.1. 使用类库好不好??还是自己实现算法1 1.2. 但是,如果遇到类库体积太大,后者没有合适的算法,那就只能自己开发算法了1 1.3. 如 ...

  2. 每日一记-mybatis碰到的疑惑:String类型可以传入多个参数吗

    碰到一个觉得很疑惑的问题,Mybatis的parameterType为String类型的时候,能够接收多个参数的吗? 背景 初学Mybatis的时候,看的教程和书籍上都是在说基本的数据类型如:int. ...

  3. 解决上一篇jquery中on的疑惑

    内容都是来自:http://www.365mini.com/page/jquery-on.htm.这里做一下收藏.文章的最后  疑问和解答可以解决所有的疑惑  看了之后能更好的整篇文章. on()函数 ...

  4. ConcurrentDictionary线程不安全么,你难道没疑惑,你难道弄懂了么?

    前言 事情不太多时,会时不时去看项目中同事写的代码可以作个参考或者学习,个人觉得只有这样才能走的更远,抱着一副老子天下第一的态度最终只能是井底之蛙.前两篇写到关于断点传续的文章,还有一篇还未写出,后续 ...

  5. Python处理json格式的数据文件(一些坑、一些疑惑)

    这里主要说最近遇到的一个问题,不过目前只是换了一种思路先解决了,脑子里仍然有疑惑,只能怪自己太菜. 最近要把以前爬的数据用一下了,先简单的过滤一下,以前用scrapy存数据的时候为了省事也为了用一下它 ...

  6. SQL Server中的索引结构与疑惑

    说实话我从没有在实际项目中使用过索引,仅知道索引是一个相当重要的技术点,因此我也看了不少文章知道了索引的区别.分类.优缺点以及如何使用索引.但关于索引它最本质的是什么笔者一直没明白,本文是笔者带着这些 ...

  7. python的正则表达式 re-------可以在字符串前加上 r 这个前缀来避免部分疑惑,因为 r 开头的python字符串是 raw 字符串,所以里面的所有字符都不会被转义

    正则表达式使用反斜杆(\)来转义特殊字符,使其可以匹配字符本身,而不是指定其他特殊的含义.这可能会和python字面意义上的字符串转义相冲突,这也许有些令人费解.比如,要匹配一个反斜杆本身,你也许要用 ...

  8. jquery 清除动画队列不疑惑

    $(this).siblings().stop().fadeTo(200, 0.3); jquery动画存在一个队列, 会把事件产生的动画 放在一个队列中,当来不及执行这些事件队列的时候,会在事件结束 ...

  9. 对Joint Training of Cascaded CNN for Face Detection一文的几点疑惑

    最近读了Joint Training of Cascaded CNN for Face Detection这篇论文,论文中把之前人脸检测使用到的cascade cnn,从分开训练的模式,改为了联合训练 ...

随机推荐

  1. CentOS7安装Oracle 11g R2 详细过程——零基础

    本人linux小白,因项目原因必须要在linux下使用oracle便开始了探索.安装过程中遇到了种种问题与原因,今天整理一下方便后面的可以少走弯路. *注明: 安装过程注意当前错作的用户,执行./ru ...

  2. IE浏览器的兼容模式代码细节解读

    兼容性对于网页设计师来说非常重要.虽然最好是建立一个完全不需依赖任何网页浏览器特性或功能的网站,但是有时候这是不可能实现的.而文件兼容模式能将网页限制在某个特定版本的IE中.可以使用 X-UA-Com ...

  3. python使用xlrd模块读写Excel文件的方法

    本文实例讲述了python使用xlrd模块读写Excel文件的方法.分享给大家供大家参考.具体如下: 一.安装xlrd模块 到python官网下载http://pypi.python.org/pypi ...

  4. java中用中国网建提供的SMS短信平台发送短信

    接下来的项目需求中提到需要短信发送功能,以前没有做过,因此便在网上搜了一下.大体上说的都是有三种方法,分别是sina提供的webservice接口.短信mao和中国网建提供的SMS短信平台. 这三种方 ...

  5. TMS320C54x系列DSP的CPU与外设——第8章 流水线

    第8章 流水线 本章描述了TMS320C54x DSP流水线的操作,列出了对不同寄存器操作时的流水线延迟周期.(对应英语原文第7章) 8.1 流水线操作 TMS320C54x DSP有一个6段的指令流 ...

  6. RMQ问题ST算法 (还需要进一步完善)

    /* RMQ(Range Minimum/Maximum Query)问题: RMQ问题是求给定区间中的最值问题.当然,最简单的算法是O(n)的,但是对于查询次数很多(设置多大100万次),O(n)的 ...

  7. MVC 安装

    mvc 4 支持window xp,window 7,window 8, mvc 4 支持vs2010,vs2012 vs2012中包含mvc4; vs2010中需要安装mvc4 安装包:

  8. ERP_Oracle Erp R12.2的新技术特点(概念)

    2014-09-09 Created By BaoXinjian

  9. Markdown 编辑模板

    Hello,我是s1124yy. 名字的由来呢,是因为我QQ前4位是1124,但有的账号不能数字开头,所以就随手打了几个字母,最后就这么叫了.其实我很菜,但是我会努力的~~ 由于看到qsc的博客,所以 ...

  10. 把vector中的string对象导入到字符指针数组中

    #include <iostream>#include <string>#include <vector>//#include <cctype>#inc ...