LimitedTaskScheduler:

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace Utils
{
public class LimitedTaskScheduler : TaskScheduler, IDisposable
{
#region 外部方法
[DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
#endregion #region 变量属性事件
private BlockingCollection<Task> _tasks = new BlockingCollection<Task>();
List<Thread> _threadList = new List<Thread>();
private int _threadCount = ;
private int _timeOut = Timeout.Infinite;
private Task _tempTask;
#endregion #region 构造函数
public LimitedTaskScheduler(int threadCount = )
{
CreateThreads(threadCount);
}
#endregion #region override GetScheduledTasks
protected override IEnumerable<Task> GetScheduledTasks()
{
return _tasks;
}
#endregion #region override TryExecuteTaskInline
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return false;
}
#endregion #region override QueueTask
protected override void QueueTask(Task task)
{
_tasks.Add(task);
}
#endregion #region 资源释放
/// <summary>
/// 资源释放
/// 如果尚有任务在执行,则会在调用此方法的线程上引发System.Threading.ThreadAbortException,请使用Task.WaitAll等待任务执行完毕后,再调用该方法
/// </summary>
public void Dispose()
{
_timeOut = ; foreach (Thread item in _threadList)
{
item.Abort();
}
_threadList.Clear(); GC.Collect();
GC.WaitForPendingFinalizers();
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -, -);
}
}
#endregion #region 创建线程池
/// <summary>
/// 创建线程池
/// </summary>
private void CreateThreads(int? threadCount = null)
{
if (threadCount != null) _threadCount = threadCount.Value;
_timeOut = Timeout.Infinite; for (int i = ; i < _threadCount; i++)
{
Thread thread = new Thread(new ThreadStart(() =>
{
Task task;
while (_tasks.TryTake(out task, _timeOut))
{
TryExecuteTask(task);
}
}));
thread.IsBackground = true;
thread.Start();
_threadList.Add(thread);
}
}
#endregion #region 全部取消
/// <summary>
/// 全部取消
/// </summary>
public void CancelAll()
{
while (_tasks.TryTake(out _tempTask)) { }
}
#endregion }
}

ThreadHelper(Run方法没有使用LimitedTaskScheduler,Run2方法使用了LimitedTaskScheduler):

using System;
using System.Windows.Threading;
using System.Threading;
using System.Threading.Tasks; namespace Utils
{
/// <summary>
/// 线程帮助类(处理单线程任务)
/// </summary>
public class ThreadHelper
{
private static LimitedTaskScheduler _defaultScheduler = new LimitedTaskScheduler(); /// <summary>
/// 执行
/// 例:ThreadHelper.Run(() => { }, (ex) => { });
/// </summary>
/// <param name="doWork">在线程中执行</param>
/// <param name="errorAction">错误处理</param>
public static System.Threading.Tasks.Task Run2(Action doWork, LimitedTaskScheduler scheduler = null, Action<Exception> errorAction = null)
{
if (scheduler == null) scheduler = _defaultScheduler;
System.Threading.Tasks.Task task = System.Threading.Tasks.Task.Factory.StartNew(() =>
{
try
{
if (doWork != null)
{
doWork();
}
}
catch (Exception ex)
{
if (errorAction != null) errorAction(ex);
LogUtil.LogError(ex);
}
}, CancellationToken.None, TaskCreationOptions.None, scheduler);
return task;
} /// <summary>
/// 执行
/// 例:ThreadHelper.Run(() => { }, (ex) => { });
/// </summary>
/// <param name="doWork">在线程中执行</param>
/// <param name="errorAction">错误处理</param>
public static System.Threading.Tasks.Task Run(Action doWork, LimitedTaskScheduler scheduler = null, Action<Exception> errorAction = null)
{
System.Threading.Tasks.Task task = System.Threading.Tasks.Task.Factory.StartNew(() =>
{
try
{
if (doWork != null)
{
doWork();
}
}
catch (Exception ex)
{
if (errorAction != null) errorAction(ex);
LogUtil.LogError(ex);
}
});
return task;
} /// <summary>
/// 封装Dispatcher.BeginInvoke
/// 例:ThreadHelper.BeginInvoke(this.Dispatcher, () => { }, (ex) => { });
/// </summary>
/// <param name="errorAction">错误处理</param>
public static void BeginInvoke(Dispatcher dispatcher, Action action, Action<Exception> errorAction = null)
{
dispatcher.InvokeAsync(new Action(() =>
{
try
{
DateTime dt = DateTime.Now;
action();
double d = DateTime.Now.Subtract(dt).TotalSeconds;
if (d > 0.01) LogUtil.Log("ThreadHelper.BeginInvoke UI耗时:" + d + "秒 " + action.Target.ToString());
}
catch (Exception ex)
{
if (errorAction != null) errorAction(ex);
LogUtil.LogError(ex);
}
}), DispatcherPriority.Background);
}
}
}

测试方法:

private void Test23()
{
//变量定义
DateTime dt = DateTime.Now;
Random rnd = new Random();
int taskCount = ;
LimitedTaskScheduler scheduler = new LimitedTaskScheduler(); //生成测试数据
BlockingCollection<double> _data = new BlockingCollection<double>();
for (int i = ; i < taskCount; i++)
{
_data.Add(rnd.NextDouble());
} //数据计算
Thread thread = new Thread(new ThreadStart(() =>
{
dt = DateTime.Now;
for (int i = ; i < taskCount; i++)
{
ThreadHelper.Run(() =>
{
Thread.Sleep();
double a;
if (_data.TryTake(out a))
{
double r = Math.PI * a;
}
}, scheduler);
}
double d = DateTime.Now.Subtract(dt).TotalSeconds; this.BeginInvoke(new Action(() =>
{
textBox1.Text += "调用" + taskCount + "次ThreadHelper.Run耗时:" + d.ToString() + "秒\r\n";
}));
}));
thread.IsBackground = true;
thread.Start(); //数据计算耗时
Thread thread2 = new Thread(new ThreadStart(() =>
{
while (_data.Count > )
{
Thread.Sleep();
}
double d = DateTime.Now.Subtract(dt).TotalSeconds; this.BeginInvoke(new Action(() =>
{
textBox1.Text += "数据计算结束,耗时:" + d.ToString() + "秒\r\n";
}));
}));
thread2.IsBackground = true;
thread2.Start(); scheduler.Dispose();
} private LimitedTaskScheduler _scheduler = new LimitedTaskScheduler();
private void Test24()
{
//点击按钮耗时
DateTime dt = DateTime.Now;
ThreadHelper.Run(() =>
{
double d = DateTime.Now.Subtract(dt).TotalSeconds;
this.BeginInvoke(new Action(() =>
{
textBox1.Text += "点击按钮耗时:" + d.ToString() + "秒\r\n";
}));
}, _scheduler);
}

事件方法:

private void button1_Click(object sender, EventArgs e)
{
Test23();
} private void button2_Click(object sender, EventArgs e)
{
Test24();
}

测试操作步骤:

依次点击3次button1和1次button2

使用Run测试结果:

使用Run2测试结果:

结论:使用Run,点击button2时,卡了好几秒才出来结果,而使用Run2,点击button2时,立即显示结果,button2的操作本身应该耗时极少。

现实意义:当一批耗时任务无脑使用Task.Factory.StartNew时,另一个使用Task.Factory.StartNew的任务就无法及时响应了。

C# Task 多任务 限制Task并发数量的更多相关文章

  1. C# 多任务之 Task

    Task 是什么 ? Task 是一个类, 它表示一个操作不返回一个值,通常以异步方式执行. Task 对象是一个的中心思想 基于任务的异步模式 首次引入.NET Framework 4 中. 继承层 ...

  2. C# 执行固定个数任务自行控制进入线程池的线程数量,多任务同时但是并发数据限定

    思路来源:http://bbs.csdn.NET/topics/390819824,引用该页面某网友提供的方法. 题目:我现在有100个任务,需要多线程去完成,但是要限定同时并发数量不能超过5个. 原 ...

  3. async和enterproxy控制并发数量

    聊聊并发与并行 并发我们经常提及之,不管是web server,app并发无处不在,操作系统中,指一个时间段中几个程序处于已经启动运行到完毕之间,且这几个程序都是在同一处理机上运行,并且任一个时间点只 ...

  4. Spring的任务调度@Scheduled注解——task:scheduler和task:executor的解析

    原文地址: https://blog.csdn.net/yx0628/article/details/80873774 一个简单的Spring定时任务的 demo,全部代码见下载地址:https:// ...

  5. 【C# Task】理解Task中的ConfigureAwait配置同步上下文

    原文:https://devblogs.microsoft.com/dotnet/configureawait-faq/ 作者:Stephen 翻译:xiaoxiaotank 静下心来,你一定会有收获 ...

  6. Task.Run Vs Task.Factory.StartNew

    在.Net 4中,Task.Factory.StartNew是启动一个新Task的首选方法.它有很多重载方法,使它在具体使用当中可以非常灵活,通过设置可选参数,可以传递任意状态,取消任务继续执行,甚至 ...

  7. Task.Run Vs Task.Factory.StartNew z

    在.Net 4中,Task.Factory.StartNew是启动一个新Task的首选方法.它有很多重载方法,使它在具体使用当中可以非常灵活,通过设置可选参数,可以传递任意状态,取消任务继续执行,甚至 ...

  8. MapReduce作业的map task和reduce task调度参数

    MapReduce作业可以细分为map task和reduce task,而MRAppMaster又将map task和reduce task分为四种状态: 1.pending:刚启动但尚未向reso ...

  9. C# Task的使用---Task的启动

    .NET 4.0包含的新名称空间System.Threading.Tasks,它包含的类抽象出了线程功能.任务表示应完成的某个单元的工作.这个单元的工作可以在单独的线程中运行,也可以以同步的方式启动一 ...

随机推荐

  1. Centos Linux下使用Metasploit渗透android

    .newline{display:block}.katex .base{position:relative;white-space:nowrap;width:min-content}.katex .b ...

  2. MyBatis的配置与使用(增,删,改,查)

    ---恢复内容开始--- Mybatis入门介绍 一.MyBatis介绍 什么是MyBtis? MyBatis 是一个简化和实现了 Java 数据持久化层(persistence layer)的开源框 ...

  3. 【华为云实战开发】9.如何进行PHP项目的快速搭建并实现CICD?【华为云技术分享】

    1 概述 1.1 文章目的 本文主要想为研发PHP项目的企业或个人提供上云指导,通过本文中的示例项目 “workerman-todpole”,为开发者提供包括项目管理,代码托管,代码检查,编译构建,测 ...

  4. 实战!轻松搭建图像分类 AI 服务

    人工智能技术(以下称 AI)是人类优秀的发现和创造之一,它代表着至少几十年的未来.在传统的编程中,工程师将自己的想法和业务变成代码,计算机会根据代码设定的逻辑运行.与之不同的是,AI 使计算机有了「属 ...

  5. 鲲鹏性能优化十板斧之前言 | 鲲鹏处理器NUMA简介与性能调优五步法

    鲲鹏处理器NUMA简介 随着现代社会信息化.智能化的飞速发展,越来越多的设备接入互联网.物联网.车联网,从而催生了庞大的计算需求.但是功耗墙问题以功耗和冷却两大限制极大的影响了单核算力的发展.为了满足 ...

  6. 基于webpack实现多html页面开发框架六 提取公共代码

    一.解决什么问题 1.如果a.js和b.js都引用了common.js,那在打包的时候common.js会被重复打入到a.js和b.js,造成重复打包 2.单独打包common.js对性能有帮助,浏览 ...

  7. hdu5969最大的位或

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=5969 题意:给定自然数l和r ,选取2个整数x,y,满足l <= x <= y <= r ...

  8. tensorflow mnist模块详解

    tensorflow的官方文档是以mnist数据集为例子开始的.文档本身没有介绍tensorflow.contrib.learn.python.learn.datasets.mnist模块.要想用te ...

  9. Selenium选择web元素

    获取html片段可以用来做什么? 可以用来分割,也可以分析HTML文档 beautifulsoup用法? 安装beautifulsoup库: pip install beautifulsoup4 因为 ...

  10. springboot中的pom文件是如何管理依赖的

    我们来看一下新建完成后的springboot中的pom文件 <?xml version="1.0" encoding="UTF-8"?> <p ...