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. ExtJS学习-----------Ext.Array,ExtJS对javascript中的Array的扩展(实例)

    (1)clean var arr = [1,2,null,3,'']; alert(Ext.Array.clean(arr)); //clean的对象:(value === null) || (val ...

  2. 推荐Java基础

    (一) 基础篇 01. Java多线程系列--“基础篇”01之 基本概念 02. Java多线程系列--“基础篇”02之 常用的实现多线程的两种方式 03. Java多线程系列--“基础篇”03之 T ...

  3. Android UI布局之LinearLayout

    LinearLayout是Android中最经常使用的布局之中的一个.它将自己包括的子元素依照一个方向进行排列.方向有两种,水平或者竖直.这个方向能够通过设置android:orientation=& ...

  4. Android加密解密

    随笔分类 - Android加密解密 Android数据加密之异或加密算法 摘要: 前言: 这几天被公司临时拉到去做Android IM即时通信协议实现,大致看了下他们定的协议,由于之前没有参与,据说 ...

  5. Eclipse SDK Android Studio 下载地址

    https://developer.android.com/sdk/index.html#download 这个网址可以下载需要的东西,FQ的话可以给 xifulinmen@gmail.com 发一个 ...

  6. information_schema系列九

    information_schema系列九   1:INNODB_SYS_FOREIGN 这个表存储的是INNODB关于外键的元数据信息 Column name Description ID 外键的名 ...

  7. [转]PHP之APC缓存详细介绍(学习整理)

    From : http://www.2cto.com/kf/201210/160140.html 1.APC缓存简介APC,全称是Alternative PHP Cache,官方翻译叫”可选PHP缓存 ...

  8. python模块uuid产生唯一id

    使用版本4:uuid4就可以了 UUID4缺点:糟糕的随机数发生器使得它更有可能发生碰撞,但是概率真的很小 UUID1缺点:暴露隐私 If all you want is a unique ID, y ...

  9. pchar,pwidechar,pansichar作为返回参数时内存访问错误

    function Test:pachr: var   str: string; begin   str := 'Test Char';   result:=pchar(str); end; 上面的Te ...

  10. [leetcode]Sqrt(x) @ Python

    原题地址:https://oj.leetcode.com/problems/sqrtx/ 题意: Implement int sqrt(int x). Compute and return the s ...