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数量由谁来决定? 一般情况下,在 ...
随机推荐
- UnionPay,ChinaPay 最新 银联支付接口C#\Asp.net\MVC 版本
1.概念普及 一.理解什么是UnionPay.ChinaPay 这两个概念如果搞不清楚,绝对够你瞎折腾一段时间的. UnionPay:中国银联,最大的机构:他本身也提供系统接口但都是B2B的,对于单个 ...
- 如何做好IT运营.
定义IT管理的重点在于业务策略与 IT 部门提供的服务之间的一致性.IT 管理可建立必要的管理机制来确保可预测的 IT 服务交付,从而确保业务流程和 IT 流程之间的联系.IT 管理传统上属于CIO. ...
- 《热血传奇2》wix、wil文件解析Java实现
在百度上搜索java+wil只有iteye上一篇有丁点儿内容,不过他说的是错的!或者说是不完整的,我个人认为我对于热血传奇客户端解析还是有一定研究的,请移步: <JMir——Java版热血传奇2 ...
- 为Eclipse添加Java和Android SDK源代码
1.添加jdk源码进入eclipse Ctrl + Click -->Attached Source 路径:D:\Program Files\Java\jdk1.8.0_45\src.zip 2 ...
- [原创]Android Handler使用Message的一个注意事项
最近发现了一个莫名其妙的问题,在使用Handler.post(Runnable)这个接口时,Runnable有时候没有运行,非常奇怪,后来发现是因为调用Handler.removeMessage()时 ...
- C代码中如何调用C++ C++中如何调用C
注意这里的C调用C++或者C++调用C意思是.c文件中调用.cpp文件中代码,或者相反. 集成开发环境如VC++6.0或者vs都是以文件后缀来区别当前要编译的是C代码还是C++代码,然后采用响应的编译 ...
- 关于STM8空间不足的解决方法
STM8虽然功能齐全,但是空间不足也是经常出来的情况.要么.text overflow,要么.bss overflow,让人头疼.这里把一些优化方案列出来,让空间得到充分利用: 1.在Project ...
- studio 快捷键
一,基础快捷键 1.1 Ctrl+N,Navigate | Class,快速打开某个类 1.2 Ctrl+Shift+N, Navigate | File, 快速打开某个文件 1.3 Ctrl+S ...
- HBase Snapshot功能介绍
HBase在0.94之后提供了Snapshot功能,一个snapshot其实就是一组metadata信息的集合,它可以让管理员将表恢复到以前的一个状态.snapshot并不是一份拷贝,它只是一个文件名 ...
- LiveWriter Test
From LiveWriter.