public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler
{
// Indicates whether the current thread is processing work items.
[ThreadStatic] private static bool _currentThreadIsProcessingItems; // The maximum concurrency level allowed by this scheduler.
private readonly int _maxDegreeOfParallelism; // The list of tasks to be executed
private readonly LinkedList<Task> _tasks = new LinkedList<Task>(); // protected by lock(_tasks) // Indicates whether the scheduler is currently processing work items.
private int _delegatesQueuedOrRunning; // Creates a new instance with the specified degree of parallelism.
public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism)
{
if (maxDegreeOfParallelism < ) throw new ArgumentOutOfRangeException("maxDegreeOfParallelism");
_maxDegreeOfParallelism = maxDegreeOfParallelism;
} // Gets the maximum concurrency level supported by this scheduler.
public sealed override int MaximumConcurrencyLevel
{
get { return _maxDegreeOfParallelism; }
} // Queues a task to the scheduler.
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();
}
}
} // Inform the ThreadPool that there's work to be executed for this scheduler.
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
TryExecuteTask(item);
}
}
// We're done processing items on the current thread
finally
{
_currentThreadIsProcessingItems = false;
}
}, null);
} // Attempts to execute the specified task on the current thread.
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)
// Try to run the task.
if (TryDequeue(task))
return TryExecuteTask(task);
else
return false;
return TryExecuteTask(task);
} // Attempt to remove a previously scheduled task from the scheduler.
protected sealed override bool TryDequeue(Task task)
{
lock (_tasks)
{
return _tasks.Remove(task);
}
} // Gets an enumerable of the tasks currently scheduled on this scheduler.
protected sealed override IEnumerable<Task> GetScheduledTasks()
{
var lockTaken = false;
try
{
Monitor.TryEnter(_tasks, ref lockTaken);
if (lockTaken) return _tasks;
else throw new NotSupportedException();
}
finally
{
if (lockTaken) Monitor.Exit(_tasks);
}
}
}

使用方法

            // Create a scheduler that uses two threads.
var lcts = new LimitedConcurrencyLevelTaskScheduler();
var tasks = new List<Task>(); // Create a TaskFactory and pass it our custom scheduler.
var factory = new TaskFactory(lcts);
var cts = new CancellationTokenSource();
var t = factory.StartNew(() =>
{ }, cts.Token);
tasks.Add(t);
Task.WaitAll(tasks.ToArray());
cts.Dispose();
或者
       Task ttt=new Task((() => {}));
       ttt.Start(lcts);
 

task 限制任务数量(转自msdn)的更多相关文章

  1. webapi+Task并行请求不同接口实例

    标题的名称定义不知道是否准确,不过我想表达的意思就是使用Task特性来同时请求多个不同的接口,然后合并数据:我想这种场景的开发对于对接过其他公司接口的人不会陌生,本人也是列属于之内,更多的是使用最原始 ...

  2. Task异步编程

    Task异步编程中,可以实现在等待耗时任务的同时,执行不依赖于该耗时任务结果的其他同步任务,提高效率. 1.Task异步编程方法签名及返回值: a) 签名有async 修饰符 b) 方法名以 Asyn ...

  3. 使用 Async 和 Await 的异步编程(C# 和 Visual Basic)[msdn.microsoft.com]

    看到Microsoft官方一篇关于异步编程的文章,感觉挺好,不敢独享,分享给大家. 原文地址:https://msdn.microsoft.com/zh-cn/library/hh191443.asp ...

  4. 微软BI 之SSIS 系列 - MVP 们也不解的 Scrip Task 脚本任务中的一个 Bug

    开篇介绍 前些天自己在整理 SSIS 2012 资料的时候发现了一个功能设计上的疑似Bug,在 Script Task 中是可以给只读列表中的变量赋值.我记得以前在 2008 的版本中为了弄明白这个配 ...

  5. Async 、 Await 的异步编程(.NET 4.5 新异步模型) [转自MSDN]

    使用异步编程,可以避免性能瓶颈和增强应用程序的总体响应能力. 但是,编写异步应用程序的以前的技术可能比较复杂,使它们难以编写,调试和维护. Visual Studio 2012 引入了一个简化的方法, ...

  6. webapi Task

    webapi+Task并行请求不同接口实例 标题的名称定义不知道是否准确,不过我想表达的意思就是使用Task特性来同时请求多个不同的接口,然后合并数据:我想这种场景的开发对于对接过其他公司接口的人不会 ...

  7. Asp.Net Core 轻松学-多线程之Task快速上手

    前言     Task是从 .NET Framework 4 开始引入的一项基于队列的异步任务(TAP)模式,从 .NET Framework 4.5 开始,任何使用 async/await 进行修饰 ...

  8. 线程(Thread,ThreadPool)、Task、Parallel

    线程(Thread.ThreadPool) 线程的定义我想大家都有所了解,这里我就不再复述了.我这里主要介绍.NET Framework中的线程(Thread.ThreadPool). .NET Fr ...

  9. 如何确定 Hadoop map和reduce的个数--map和reduce数量之间的关系是什么?

    1.map和reduce的数量过多会导致什么情况?2.Reduce可以通过什么设置来增加任务个数?3.一个task的map数量由谁来决定?4.一个task的reduce数量由谁来决定? 一般情况下,在 ...

随机推荐

  1. lua中常量的实现及表的深拷贝实现

    废话:好久没在这里写博客了...主要原因是我买了个域名hanxi.info并在github上搭建了个人博客... lua中默认是没有c中的const常量的,在csdn上找到了一个使用setmetata ...

  2. ecshop 加广告出现广告位的宽度值必须在1到1024之间

    打开 admin/ad_position.php这个文件,搜索1024,这里你会搜到两个地方 在236行左右 if ($ad_width > 1024 || $ad_width < 1) ...

  3. [转载] Calculating Entropy

    From:  johndcook.com/blog For a set of positive probabilities pi summing to 1, their entropy is defi ...

  4. C#集合-列举(Enumeration)

    在计算机这个范畴内存在许多种类的集合,从简单的数据结构比如数组.链表,到复杂的数据结构比如红黑树,哈希表.尽管这些数据结构的内部实现和外部特征大相径庭,但是遍历集合的内容确是一个共同的需求..NET ...

  5. netbeans项目中排除node_modules文件夹

    由于项目中的javascript使用了gulp编译技术,所以在web目录下有js的源码目录,其中又有gulp所使用的nodeJS模块,node_modules下面小文件很多,所以造成netbeans扫 ...

  6. 一次受限于操作系统进程数的OOM

    在64bit机上跑应用,结果进程刚起来就挂,就刚起来就挂..还OOM,还fork不出新进程,尼玛,这什么情况? 1. 如果是应用层面OOM,那么不应该任何命令都不被执行了,不应该OS直接crash掉. ...

  7. java之Object类介绍

    1.Object类是所有java类的基类 如果在类的声明中未使用extends关键字指明其基类,则默认基类为Object类,ex: public class Person{ ~~~~~ } 等价于 p ...

  8. winedt设置自动显示行号[latex]

    options--preferences--appearance 在show line numbers for modes下面的文本框里添加;Tex 这样新建或者打开tex文件的时候就自动显示行号了( ...

  9. Ubuntu下的杀毒

      Ubuntu 11.04 杀毒软件ESET NOD32   Linux防病毒,并不代表没有病毒,只是数量过少.因技术精英发现漏洞后即时打补丁,病毒很少. 有兴趣的同学可以尝试下Ubuntu 11. ...

  10. myeclipse 2013 SR2 for(MAC/WINDOWS)破解 注册过程

    前天去官网下载的时候都还只是sr1,结果昨天去看居然有sr2了,之前一直在windows下用 2013,网上的注册机都还很好用.但最近换了mac,下载的sr1我却无论如何都没办法破解,下载了N个版本的 ...