task 限制任务数量(转自msdn)
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)的更多相关文章
- webapi+Task并行请求不同接口实例
标题的名称定义不知道是否准确,不过我想表达的意思就是使用Task特性来同时请求多个不同的接口,然后合并数据:我想这种场景的开发对于对接过其他公司接口的人不会陌生,本人也是列属于之内,更多的是使用最原始 ...
- Task异步编程
Task异步编程中,可以实现在等待耗时任务的同时,执行不依赖于该耗时任务结果的其他同步任务,提高效率. 1.Task异步编程方法签名及返回值: a) 签名有async 修饰符 b) 方法名以 Asyn ...
- 使用 Async 和 Await 的异步编程(C# 和 Visual Basic)[msdn.microsoft.com]
看到Microsoft官方一篇关于异步编程的文章,感觉挺好,不敢独享,分享给大家. 原文地址:https://msdn.microsoft.com/zh-cn/library/hh191443.asp ...
- 微软BI 之SSIS 系列 - MVP 们也不解的 Scrip Task 脚本任务中的一个 Bug
开篇介绍 前些天自己在整理 SSIS 2012 资料的时候发现了一个功能设计上的疑似Bug,在 Script Task 中是可以给只读列表中的变量赋值.我记得以前在 2008 的版本中为了弄明白这个配 ...
- Async 、 Await 的异步编程(.NET 4.5 新异步模型) [转自MSDN]
使用异步编程,可以避免性能瓶颈和增强应用程序的总体响应能力. 但是,编写异步应用程序的以前的技术可能比较复杂,使它们难以编写,调试和维护. Visual Studio 2012 引入了一个简化的方法, ...
- webapi Task
webapi+Task并行请求不同接口实例 标题的名称定义不知道是否准确,不过我想表达的意思就是使用Task特性来同时请求多个不同的接口,然后合并数据:我想这种场景的开发对于对接过其他公司接口的人不会 ...
- Asp.Net Core 轻松学-多线程之Task快速上手
前言 Task是从 .NET Framework 4 开始引入的一项基于队列的异步任务(TAP)模式,从 .NET Framework 4.5 开始,任何使用 async/await 进行修饰 ...
- 线程(Thread,ThreadPool)、Task、Parallel
线程(Thread.ThreadPool) 线程的定义我想大家都有所了解,这里我就不再复述了.我这里主要介绍.NET Framework中的线程(Thread.ThreadPool). .NET Fr ...
- 如何确定 Hadoop map和reduce的个数--map和reduce数量之间的关系是什么?
1.map和reduce的数量过多会导致什么情况?2.Reduce可以通过什么设置来增加任务个数?3.一个task的map数量由谁来决定?4.一个task的reduce数量由谁来决定? 一般情况下,在 ...
随机推荐
- WOL远程开机
最近在一直都在研究PC机硬件和软件相结合的软件,硬件信息都是通过C++与驱动结合获取.对于一个好久都没有接触C++的人来说看这些东西太费劲了,必须的重新捡一下C++的基础知识,必然也少不了C知识,底层 ...
- Asp.net Core 1.0.1升级到Asp.net Core 1.1.0 Preview版本发布到Windows Server2008 R2 IIS中的各种坑
Asp.net Core 1.0.1升级到Asp.net Core 1.1.0后,程序无法运行了 解决方案:在project.json中加入runtime节点 "runtimes" ...
- Visual Studio 2010配置Opencv2.4.9
转自: http://blog.csdn.net/huang9012/article/details/21811129 这篇文章作为OpenCV的启程篇,自然少不了先系统地介绍OpenCV开发环境的配 ...
- struts2:struts.xml配置文件详解
1. 几个重要的元素 1.1 package元素 package元素用来配置包.在Struts2框架中,包是一个独立的单位,通过name属性来唯一标识包.还可以通过extends属性让一个包继承另一个 ...
- Windows下Git安装指南
参考<Git权威指南>安装整理,图书配套网址参见[1] 1. Cygwin下安装配置Git 1. 在Windows下安装配置Git有2种不同的方案 (1)msysGit, (2)Cygwi ...
- Freemyapps赚取积分终极图文教程
Freemyapps怎么赚积分.Clash of Clans宝石获得技巧的终极教程来啦~此教程详细指导大家一步步的成功获取大量积分,买5个农民神马的自然不再话下.当然,人民币玩家可以略过~ 原文作 ...
- android 模拟器
参考:http://www.syscs.com/node/504 --skin WVGA800 - -no-boot-anim -wipe-: the dpi for the device you a ...
- 对依赖倒置原则(DIP)及Ioc、DI、Ioc容器的一些理解
1.概述 所谓依赖倒置原则(Dependence Inversion Principle)就是要依赖于抽象,不要依赖于具体.简单的说就是要求对抽象进行编程,不要对实现进行编程,这样就降低了客户与实现模 ...
- Webkit CSS properties
Webkit CSS properties -webkit-animation -webkit-animation-delay -webkit-animation-direction -webkit- ...
- Scene视图辅助线绘制
有时候需要在Scene视图中绘制一些辅助线,方便进行一些编辑的工作,可以通过如下类和函数完成: 绘制辅助线,相关类: Gizmos类:用于在Scene视图中绘制调试信息或辅助线,这些辅助线只有在Sce ...