展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 编程开发 > C#TaskTaskFactory设置最大并行线程数的方法

C#TaskTaskFactory设置最大并行线程数的方法

LimitedConcurrencyLevelTaskScheduler继承TaskScheduler,通过链表存储待执行任务,设定最大并发数。QueueTask将任务加入链表尾部,若当前运行委托数小于最大值则递增计数并调用ThreadPool.UnsafeQueueUserWorkItem启动工作线程。工作线程循环从链表取出任务执行直至队列为空,减少运行计

本文目录

    1. LimitedConcurrencyLevelTaskScheduler 介绍

    这个TaskScheduler,接触过.NET并发编程的同学应该不陌生——微软开源的一个任务调度器,代码本身确实不长,逻辑也算直白。不过,有一个问题值得琢磨:它到底是怎么实现并发数限制的?

    C#TaskTaskFactory设置最大并行线程数的方法

    先把源码贴出来,大家一起熟悉一下。

    public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler
    {
        /// Whether the current thread is processing work items. 
        [ThreadStatic]
        private static bool _currentThreadIsProcessingItems;
        /// The list of tasks to be executed. 
        private readonly LinkedList _tasks = new LinkedList(); // protected by lock(_tasks) 
                                                                           /// The maximum concurrency level allowed by this scheduler. 
        private readonly int _maxDegreeOfParallelism;
        /// Whether the scheduler is currently processing work items. 
        private int _delegatesQueuedOrRunning = 0; // protected by lock(_tasks) 
        ///  
        /// Initializes an instance of the LimitedConcurrencyLevelTaskScheduler class with the 
        /// specified degree of parallelism. 
        ///  
        /// The maximum degree of parallelism provided by this scheduler. 
        public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism)
        {
            if (maxDegreeOfParallelism < 1) throw new ArgumentOutOfRangeException("maxDegreeOfParallelism");
            _maxDegreeOfParallelism = maxDegreeOfParallelism;
        }
        /// 
        /// current executing number;
        /// 
        public int CurrentCount { get; set; }
        /// Queues a task to the scheduler. 
        /// The task to be queued. 
        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)
            {
                Console.WriteLine("Task Count : {0} ", _tasks.Count);
                _tasks.AddLast(task);
                if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism)
                {
                    ++_delegatesQueuedOrRunning;
                    NotifyThreadPoolOfPendingWork();
                }
            }
        }
        int executingCount = 0;
        private static object executeLock = new object();
        ///  
        /// Informs 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 a vailable 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);
        }
        /// Attempts to execute the specified task on the current thread. 
        /// The task to be executed. 
        ///  
        /// Whether the task could be executed 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) TryDequeue(task);
            // Try to run the task. 
            return base.TryExecuteTask(task);
        }
        /// Attempts to remove a previously scheduled task from the scheduler. 
        /// The task to be removed. 
        /// Whether the task could be found and removed. 
        protected sealed override bool TryDequeue(Task task)
        {
            lock (_tasks) return _tasks.Remove(task);
        }
        /// Gets the maximum concurrency level supported by this scheduler. 
        public sealed override int MaximumConcurrencyLevel { get { return _maxDegreeOfParallelism; } }
        /// Gets an enumerable of the tasks currently scheduled on this scheduler. 
        /// An enumerable of the tasks currently scheduled. 
        protected sealed override IEnumerable 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);
            }
        }
    }

    简单使用

    下面是调用示例,非常简单:

    static void Main(string[] args)
    {
            TaskFactory fac = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(5));
            //TaskFactory fac = new TaskFactory();
            for (int i = 0; i < 1000; i++)
            {
                fac.StartNew(s => {
                    Thread.Sleep(1000);
                    Console.WriteLine("Current Index {0}, ThreadId {1}",s,Thread.CurrentThread.ManagedThreadId);
                }, i);
            }
            Console.ReadKey();
    }

    调用逻辑很清晰:用 LimitedConcurrencyLevelTaskScheduler 创建 TaskFactory,然后通过 StartNew 提交任务。从调试顺序可以看到,每次 StartNew 都会进入 QueueTask 方法。

    /// Queues a task to the scheduler. 
        /// The task to be queued. 
        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)
            {
                Console.WriteLine("Task Count : {0} ", _tasks.Count);
                _tasks.AddLast(task);
                if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism)
                {
                    ++_delegatesQueuedOrRunning;
                    NotifyThreadPoolOfPendingWork();
                }
            }
        }
        

    QueueTask 的步骤很简单:把新任务追加到链表尾部,然后检查当前正在运行或已排队的委托数量(_delegatesQueuedOrRunning)是否小于设定的最大并发数。如果小于,就递增计数并调用 NotifyThreadPoolOfPendingWork 去启动一个工作线程。

    但真正的疑问,恰恰出在这个 NotifyThreadPoolOfPendingWork 方法上。

    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 a vailable 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);
        }

    看这个方法的内部逻辑:它直接丢了一个死循环到线程池里,循环内不断从 _tasks 中取出任务执行,直到队列为空才退出循环。这看起来就像是一个“无限吞噬”的过程——一旦启动,就会把所有任务吃光,根本看不到任何限制并发数的机制。

    唯一能扯上“限制”的地方,是 QueueTask 里那个 if 判断:只有当前执行线程数小于最大并发度时,才调用 NotifyThreadPoolOfPendingWork。但这似乎没什么用,因为一旦调用,这个工作线程就会一直跑,直到把队列清空。这样一来,并发度不就失控了吗?

    那么问题来了:LimitedConcurrencyLevelTaskScheduler 到底是如何实现并发数限制的?

    是不是哪里理解有偏差?比如,NotifyThreadPoolOfPendingWork 中 while 循环每次取任务时,会不会因为锁的竞争或其他机制而自然阻塞?但实际上锁只会保护 _tasks 的访问,并不控制线程数量。更关键的是,QueueTask 中的 if 条件保证了同时只有 _maxDegreeOfParallelism 个线程被启动,但每个线程都是“死循环”,这会不会导致任务被一个线程全部执行完,其他线程根本拿不到任务?

    仔细想想,死循环本身并不占用多个线程——它只用当前这一个线程。但问题在于,当多个任务同时被提交时,QueueTask 可能被多次调用(来自不同的调用线程),而每次调用如果满足条件都会启动一个新的工作线程。假设并发数设为5,在任务提交的瞬间,如果同时有10个线程调用 QueueTask,前5个会启动工作线程,后5个不会。但前5个工作线程各自进入死循环,彼此独立地从 _tasks 中取任务——这确实实现了5个线程同时消费任务。真正的限制在于:不会启动超过5个工作线程。而死循环保证了每个工作线程会持续消费任务,而不是执行一个就退出,这样即便后续有新任务加入,也无需再启动新线程(因为现有工作线程还在循环中)。

    换句话说,这个设计的精巧之处在于:工作线程采用“持续消费”模式,而不是“消费一次就结束”。QueueTask 中的 if 判断确保了最多只有 _maxDegreeOfParallelism 个工作线程存在,而这些线程会一直循环直到队列为空,从而实现了并发度的硬限制。

    当然,这个实现有一个潜在的缺陷:如果任务生产速度远大于消费速度,工作线程会一直忙,但一旦队列为空,工作线程退出,后续新任务到来时,如果此时 _delegatesQueuedOrRunning 已经减到小于 _maxDegreeOfParallelism,就会重新启动新工作线程。这个计数更新是在 while 循环退出时(_tasks.Count == 0)进行的,所以是安全的。

    所以,回过头来看,这个调度器对并发数的限制,本质上是通过控制“同时运行的工作线程数量”来实现的。虽然每个工作线程内部是个死循环,但死循环的线程数量是固定的,因此并发度也就固定了。

    以上是个人理解,不知是否完全准确。如果有不同看法或者更深入的分析,欢迎交流讨论。

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发
    相关文章 更多
    精品专题 更多
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    macOS软件

    正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

    IOS软件

    正软商城iOS软件专区,精选适用于iPhone和iPad的办公、学习、影音、设计、效率及AI应用,提供功能介绍、适用设备、系统要求和正版获取方式等信息。

    AI

    正软商城AI软件专区,汇集AI写作、AI绘画、AI视频、AI办公、AI编程、AI翻译、智能客服和数据分析等人工智能工具,提供功能介绍、适用平台、收费方式及正版购买信息。

    Mac软件 更多
    Postman macOS版
    Postman macOS版

    Postman是一套面向API全生命周期的开发与测试平台,可在Mac上发送和调试多种协议请求,管理集合、环境及认证信息,并完成脚本测试、模拟服务、监控、文档发布和团队协作。它适合开发、测试及运维人员使用,提供个人免费方案。

    Docker Desktop macOS版
    Docker Desktop macOS版

    Docker Desktop 是 Docker 官方为 Mac 提供的容器开发环境,集成 Docker Engine、命令行工具、Compose、Build、Kubernetes 与图形化管理界面。

    Android Studio macOS版
    Android Studio macOS版

    Android Studio 是 Google 面向安卓应用开发提供的官方集成开发环境,基于 IntelliJ IDEA 构建。它整合智能代码编辑、Gradle 构建、界面预览、设备模拟、性能分析、调试测试及 APK 分析等工具。

    Xcode macOS版
    Xcode macOS版

    Xcode 是苹果面向 Mac 提供的官方集成开发环境,将代码编辑、项目构建、SwiftUI 实时预览、设备模拟、自动化测试、断点调试、性能分析和应用分发整合在同一套工作流中,适合开发与维护 iPhone、iPad、Mac、Apple Wa

    JetBrains WebStorm macOS版
    JetBrains WebStorm macOS版

    JetBrains WebStorm 是面向 JavaScript、TypeScript 和现代 Web 技术的专业集成开发环境,可智能理解项目结构,提供代码补全、重构、错误检查、运行调试、测试及 Git 工具。

    PhpStorm macOS版
    PhpStorm macOS版

    PhpStorm 是 JetBrains 推出的专业 PHP 集成开发环境,可在 Mac 上完成代码编写、智能检查、重构、调试、测试和数据库管理。它支持主流 PHP 框架、Composer、Git、Docker 与远程解释器。

    JetBrains PyCharm macOS版
    JetBrains PyCharm macOS版

    JetBrains PyCharm 是面向 Python 开发者的集成开发环境,提供智能补全、代码检查、重构、调试、测试、版本控制及虚拟环境管理功能。Mac 版兼容 Intel 与 Apple 芯片,核心功能可免费使用。

    JetBrains IntelliJ IDEA macOS版
    JetBrains IntelliJ IDEA macOS版

    IntelliJ IDEA 是 JetBrains 推出的专业集成开发环境,重点服务于 Java、Kotlin 与 JVM 项目开发。软件集成代码补全、静态检查、重构、调试、测试、版本控制及构建工具,并可借助插件扩展语言和框架支持。

    Visual Studio Code macOS版
    Visual Studio Code macOS版

    Visual Studio Code 是微软提供的免费代码编辑器,支持 macOS,并为 Intel 与 Apple 芯片 Mac 提供适配版本。软件集代码编辑、调试、Git 源代码管理、集成终端和扩展市场于一体。

    REAPER macOS版
    REAPER macOS版

    REAPER是Cockos开发的数字音频工作站,提供多轨音频与MIDI录制、剪辑、处理、混音和母带制作工具。Mac版兼容Intel与Apple芯片,支持AU、VST、VST3、CLAP等插件格式,并提供高度可定制的工作流程。

    Adobe Audition macOS版
    Adobe Audition macOS版

    Adobe Audition 是面向播客、影视后期、音乐制作及内容创作者的专业音频工作站,提供波形精修、多轨录制与混音、频谱编辑、降噪修复、响度匹配和效果处理工具,并可与 Adobe Premiere 协同完成视频声音制作。

    Pro Tools macOS版
    Pro Tools macOS版

    Pro Tools 是 Avid 推出的专业数字音频工作站,覆盖多轨录音、无损剪辑、MIDI 编曲、插件处理、自动化混音及声音与画面同步等工作。它拥有 Intro、Artist、Studio 和 Ultimate 等方案。

    WINDOWS 更多
    PixPix 网页版
    PixPix 网页版

    PixPix 是面向品牌、卖家和内容团队的在线 AI 图片视频创作平台,提供图视频 Agent、无限画布、图片生成、视频生成、自然语言编辑及商品套图、产品精修和带货视频等电商工具。

    Postman Windows版
    Postman Windows版

    Postman 是面向 API 全生命周期的开发与协作平台。Windows 桌面版可用于构建和发送 HTTP、GraphQL、gRPC、WebSocket、MQTT 等请求,并提供环境变量、集合、脚本测试、模拟服务、监控、文档及团队工作区等

    Docker Desktop Windows版
    Docker Desktop Windows版

    Docker Desktop 为 Windows 开发者提供集成式容器环境,内置 Docker Engine、命令行工具、Compose、Build 与 Kubernetes 等组件,可在本机完成镜像构建、容器运行、日志查看和资源管理。

    Android Studio Windows版
    Android Studio Windows版

    Android Studio 是 Google 面向 Android 应用开发提供的官方集成开发环境,以 IntelliJ IDEA 为基础,集成智能代码编辑、Gradle 构建、设备模拟、界面预览、调试测试及性能分析工具,

    JetBrains WebStorm Windows版
    JetBrains WebStorm Windows版

    WebStorm 是 JetBrains 面向 JavaScript、TypeScript 和现代 Web 技术打造的集成开发环境。它提供项目级代码分析、智能补全、安全重构、导航搜索,并集成调试、测试、终端、Git 与常用前端工具,

    JetBrains PhpStorm Windows版
    JetBrains PhpStorm Windows版

    PhpStorm 是 JetBrains 面向 PHP 与现代 Web 开发打造的专业集成开发环境,提供代码补全、静态检查、重构、调试、测试、数据库、版本控制及前端语言支持。Windows 用户可直接下载安装程序,

    JetBrains PyCharm Windows版
    JetBrains PyCharm Windows版

    PyCharm 是 JetBrains 推出的 Python 集成开发环境,提供智能代码补全、错误检查、重构、调试、测试、Git、终端及 Jupyter Notebook 支持。统一版安装后可体验 30 天 Pro 功能,

    JetBrains IntelliJ IDEA Windows版
    JetBrains IntelliJ IDEA Windows版

    JetBrains IntelliJ IDEA 是以 Java、Kotlin 和 JVM 项目为核心的专业集成开发环境,提供智能补全、代码检查、安全重构、调试、测试、版本控制及构建工具集成。统一发行版的核心功能可免费用于商业和非商业项目,

    Visual Studio Code Windows版
    Visual Studio Code Windows版

    Visual Studio Code 是微软推出的免费代码编辑器,Windows 版集成智能补全、代码导航、调试、终端和版本控制,并可通过扩展添加语言、格式化及远程开发能力。它启动较快、配置灵活,

    REAPER Windows版
    REAPER Windows版

    REAPER 是 Cockos 推出的数字音频工作站,适用于录音、MIDI 编曲、音频编辑、混音、母带制作及声音设计。软件安装包小巧,支持多轨录制、灵活路由、自动化、第三方插件和脚本扩展,并提供完整功能的 60 天免费评估期。

    Adobe Audition Windows版
    Adobe Audition Windows版

    Adobe Audition 是面向播客、影视后期、广播与音乐制作的专业音频工作站,提供波形编辑、多轨混音、频谱分析、录音、降噪修复和效果处理等功能。Windows 版通过 Adobe Creative Cloud 安装和管理,

    Pro Tools Windows版
    Pro Tools Windows版

    Pro Tools 是 Avid 推出的专业数字音频工作站,提供多轨录音、音频剪辑、MIDI编曲、插件处理、自动化混音及影视声音制作能力。它适合音乐人、录音师、制作人和音频后期团队使用,并提供免费入门版、订阅方案及永久授权选择。