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. ECShop商品详细页 实现尺码颜色关联显示库存数量

    效果如下: 要开模板文件 goods.dwt  把选择尺码跟颜色的代码替换成如下,(不同模板代码可能不一样,对照去替换) <!-- {foreach from=$spec.values item ...

  2. emoji和utf8mb4字符集

    mysql 的 utf8 不支持 emoji,需要修改设置为utf8mb4 <?php 'mysql' => [ 'charset' => 'utf8mb4', 'collation ...

  3. wwdc2016-session707 Notifications(draft)

    Introduction to Notificationshttps://developer.apple.com/wwdc2016/707 通知这哥们说话有点不清晰啊. 远程通知本地通知 可以被操作的 ...

  4. 同时大量连接导致的DDOS攻击,导致收发器宕机,用户大面积超时掉线

    前段时间一个客户改成电信网通自动路由后(当然和这个没有关系,但是客户一般没有分析能力,会多想),用户经常大面积掉线,用户才180多个,在线最多也才120多,十分苦恼,原先帮其维护的技术人员,只是远程诊 ...

  5. 在Linux下用源码编译安装apache2

    Linux下安装一个软件,最好去看下它的官方guide,apache2.4的安装安装guide 0. installation guide http://httpd.apache.org/docs/2 ...

  6. HTML5图片旋转

    HTML5图片旋转 首先我们使用Cococs2dx-Js-Lite版,来创建一个工程,我们所需要的开发环境如下: 1,webstrom 2,google chrome浏览器 3,cocos2dx-Js ...

  7. [原]OpenGL基础教程(五)缓冲区数据更新方式

    1.glBufferSubData 适用于相同数据类型 void SetPositionY(float y){    vector<Vector3<float>>::itera ...

  8. 物料分类账 [COML] PART 1 - 概览

    物料分类账 [COML] PART 1 - 概览 一).原理 1). •实际成本/物料分类帐是产品成本控制模块的一个子模块,产品成本控制包括三个子模块,产品成本计划,成本对象控制,实际成本/物料分类帐 ...

  9. springmvc下使用kaptcha做验证码

    http://www.open-open.com/lib/view/open1395238908947.html

  10. ux.plugin.ConTpl 模版元素监听扩展

    /* *tpl模版加入按钮 *<div class="x-button-normal x-button x-iconalign-center x-layout-box-item x-s ...