Task对象很多人知道了(使用Task代替ThreadPool和Thread
C#线程篇—Task(任务)和线程池不得不说的秘密(5))

相对的还有TaskScheduler 这个调度器,可以自定义调度器,只要重写TaskScheduler 方法就可以了 
微软原来一早就对他进行了扩展Samples for Parallel Programming with the .NET Framework

转一下MSDN里的定义和调用方法

namespace System.Threading.Tasks.Schedulers
{ using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading; class Program
{
static void Main()
{
LimitedConcurrencyLevelTaskScheduler lcts = new LimitedConcurrencyLevelTaskScheduler(1);
TaskFactory factory = new TaskFactory(lcts); factory.StartNew(()=>
{
for (int i = 0; i < 500; i++)
{
Console.Write("{0} on thread {1}", i, Thread.CurrentThread.ManagedThreadId);
}
}
); Console.ReadKey();
}
} /// <summary>
/// Provides a task scheduler that ensures a maximum concurrency level while
/// running on top of the ThreadPool.
/// </summary>
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>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)
{
_tasks.AddLast(task);
if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism)
{
++_delegatesQueuedOrRunning;
NotifyThreadPoolOfPendingWork();
}
}
} /// <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);
}
}
}
}

TaskFactory设置并发量的更多相关文章

  1. lr并发量和迭代的区别

    1.并发量 并发量也就是同时运行的量.比如100个用户同时登录,那么并发量就是100.当然这100个用户可以进行参数化,也可以采用设置虚拟用户数(vuser). 2.迭代 迭代就是单个用户运行的次数. ...

  2. Python- redis缓存 可达到瞬间并发量10W+

    redis是什么? mysql是一个软件,帮助开发者对一台机器的硬盘进行操作. redis是一个软件,帮助开发者对一台机器的内存进行操作. redis缓存 可达到瞬间并发量10W+ 高并发架构系列:R ...

  3. 【杂谈】Spring Boot 默认支持的并发量

    Spring Boot应用支持的最大并发量是多少? Spring Boot 能支持的最大并发量主要看其对Tomcat的设置,可以在配置文件中对其进行更改.当在配置文件中敲出max后提示值就是它的默认值 ...

  4. C#不用union,而是有更好的方式实现 .net自定义错误页面实现 .net自定义错误页面实现升级篇 .net捕捉全局未处理异常的3种方式 一款很不错的FLASH时种插件 关于c#中委托使用小结 WEB网站常见受攻击方式及解决办法 判断URL是否存在 提升高并发量服务器性能解决思路

    C#不用union,而是有更好的方式实现   用过C/C++的人都知道有个union,特别好用,似乎char数组到short,int,float等的转换无所不能,也确实是能,并且用起来十分方便.那C# ...

  5. nginx配置优化提高并发量

    1 nginx配置优化提高并发量 worker_processes 2; 这个按照CPU的核数来决定 2 worker_connections 65535; 这个一般设置65535即可 每个进程允许的 ...

  6. Spring Boot 默认支持的并发量

    Spring Boot应用支持的最大并发量是多少? Spring Boot 能支持的最大并发量主要看其对Tomcat的设置,可以在配置文件中对其进行更改.当在配置文件中敲出max后提示值就是它的默认值 ...

  7. Nginx优化_访问并发量(进程可以打开的最大文件数量)

    如果客户端访问服务器提示“Too many open files”如何解决? [root@proxy ~]# ab -n 2000 -c 2000 http://192.168.1.100/    # ...

  8. 针对web高并发量的处理

    针对web高并发量的处理 针对高并发量的处理 一个老生常谈的话题了 至于需要运维支持的那些cdn.负载均衡神马的就不赘述了 你们都懂的 虫子在此博文只讲一些从程序角度出发的一些不错的解决方案. 至于从 ...

  9. cuda(1) 最大并发量

    Created on 2013-8-5URL : http://blog.sina.com.cn/s/blog_a502f1a30101mi6t.html@author: zhxfl转载请说明出处 c ...

随机推荐

  1. python测试开发django-37.外键(ForeignKey)查询

    前言 前面在admin后台页面通过设置外键,可以选择下拉框的选项,本篇主要讲解关于外键(ForeignKey)的查询 models设计 在上一篇的基础上新增一个BankName表,Card表通过外键关 ...

  2. log4j1修改DailyRollingFileAppender支持日志最大数量

    配置说明: log4j.appender.logfile=org.apache.log4j.MyDailyRollingFileAppender log4j.appender.logfile.File ...

  3. 黑吃黑第一季/全集Banshee迅雷下载

    第一季 Banshee Season 1 (2013)看点:“Banshee”在爱尔兰盖尔语中被称为“bean sidhe”,意思是“拥有超能力的女人”.不过在鲍尔的新剧中,Banshee并不是指超自 ...

  4. Oracle初级性能优化总结

    前言 关于对Oracle数据库查询性能优化的一个简要的总结. 从来数据库优化都是一项艰巨的任务.对于大数据量,访问频繁的系统,优化工作显得尤为重要.由于Oracle系统的灵活性.复杂性.性能问题的原因 ...

  5. 开源项目PullToRefresh详解(二)——PullToRefreshGridView

    这里介绍的是PullToRefreshGridView的使用方法,和之前的PullToRefreshListView方法如出一辙,因为这个开源项目模块化很棒,所以很容易实现.等于说我们可以按照之前使用 ...

  6. [Android Pro] 自己动手编译Android源码(超详细)

    cp from : https://www.jianshu.com/p/367f0886e62b 在Android Studio代码调试一文中,简单的介绍了代码调试的一些技巧.现在我们来谈谈andro ...

  7. [转]php判断一个数组是另一个数组的子集

    FROM : http://blog.csdn.net/lcion/article/details/8985220 今天完成一个算法的过程中,有几个需求模块,其中就有判断$a数组是否是$b数组的子集, ...

  8. Zookeeper Tutorial 1 -- Overview

    ZooKepper: 一个分布式应用的分布式协调服务(Distributed Coordination Service) 分布式服务难以管理, 他们容易造成死锁和竞争, ZooKepper的动机就是为 ...

  9. ASP.NET MVC 中使用JavaScriptResult asp.net mvc 返回 JavaScript asp.mvc 后台返回js

    return this.Content("<script>alert('暂无!');window.location.href='/Wap/Index';</script&g ...

  10. 7.7 服务远程暴露 - 订阅与通知(TODO)

    为了安全:服务启动的ip全部使用10.10.10.10 远程服务的暴露总体步骤: 将ref封装为invoker 将invoker转换为exporter 启动netty 注册服务到zookeeper 订 ...