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. Java Calendar,Date,DateFormat,TimeZone,Locale等时间相关内容的认知和使用(5) SimpleDateFormat

    本章介绍SimpleDateFormat. SimpleDateFormat 介绍 SimpleDateFormat 是一个格式化Date 以及 解析日期字符串 的工具.它的最常用途是,能够按照指定的 ...

  2. ASIHTTPRequestErrorDomain Code=5

    ASIHttpRequest解析带空格的URL时 出错!!!(已解决) 用的是post请求 URL 地址是: http://111.234.51.56/login_member.pl?time=201 ...

  3. uitextfield 设置为密码框显示

    uitextfield 设置为密码框显示: 在xib中,将文本secure的复选框选中即可.

  4. 【CentOS】centos7 稳定使用版本,centos镜像的下载

    命令: cat /etc/redhat-release 下载地址: https://wiki.centos.org/Download 下载版本:

  5. android ActionBarImpl can only be used with a compatible window decor layout

    在Activity中添加 requestWindowFeature(Window.FEATURE_ACTION_BAR); requestWindowFeature(Window.FEATURE_AC ...

  6. dev的documentManager,多个tab窗体

    private void AddDocument(Funcation CurrentModel) { if (!string.IsNullOrWhiteSpace(CurrentModel.Funct ...

  7. SharePoint 列表视图修改多行文本字段显示长度

    前言 最近有这么个需求,用户希望在所有项目视图显示多行文本字段,然后,又不希望显示的过场,也就是处理一下长度. 一开始就想到用js的方式去处理,偶然间发现还可以用jslink,尝试了一下,非常好用,分 ...

  8. 通过xml文件来设置动画

    @android:anim/accelerate_interpolator: 越来越快 @android:anim/decelerate_interpolator:越来越慢 @android:anim ...

  9. yolo源码解析(一)

    原文:https://www.cnblogs.com/zyly/p/9534063.html yolo源码来源于网址:https://github.com/hizhangp/yolo_tensorfl ...

  10. 虚拟机内存复用技术的比较(XEN系统)

    技术途径 业界就该问题定义为虚拟机内存复用(复用干嘛? 当然是为了跑更多的虚拟机呀!) :memory overcommit.围绕次问题主要有4种技术手段,下面简要介绍和分析: 1 气泡驱动(ball ...