C#学习系列相关之多线程(五)----线程池ThreadPool用法

一、线程池的作用

        线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池线程都是后台线程。每个线程都使用默认堆栈大小,以默认的优先级运行,并处于多线程单元中。如果某个线程在托管代码中空闲(如正在等待某个事件),则线程池将插入另一个辅助线程来使所有处理器保持繁忙。如果所有线程池线程都始终保持繁忙,但队列中包含挂起的工作,则线程池将在一段时间之后创建另一个辅助线程。但线程的数目永远不会超过最大值。超过最大值的其他线程可以排队,但它们要等到其他线程完成后才启动。

线程池的使用范围: 

(1)不需要前台执行的线程。

(2)不需要在使用线程具有特定的优先级。

(3)线程的执行时间不易过长,否则会使线程阻塞。由于线程池具有最大线程数限制,因此大量阻塞的线程池线程可能会阻止任务启动。

(4)不需要将线程放入单线程单元。所有 ThreadPool 线程均不处于多线程单元中。

(5)不需要具有与线程关联的稳定标识,或使某一线程专用于某一任务。
 

二、常用方法介绍

1.ThreadPool.QueueUserWorkItem

        该方法是线程池中最主要的方法,ThreadPool.QueueUserWorkItem 方法是用于将工作项提交到线程池队列中的方法。当你需要执行一个方法但不想创建一个新的线程时,可以使用该方法。这个方法会将工作项放到一个线程池队列中,并由线程池中的一个线程来执行该工作项。

 ThreadPool.QueueUserWorkItem(WaitCallback(DoWork), object)

该方法主要是两个参数,第一个是WaitCallback,第二个是一个object,object参数可以作为WaitCallback方法的参数传入。

public delegate void WaitCallback(object state);

 WaitCallback是一个委托类型,委托参数类型是object定义,因此传入WaitCallback的方法也应当是object类型。

codepublic static void DoWork(object state)
{// 执行一些操作,使用传递进来的状态对象
}static void Main(string[] args)
{// 将 DoWork 方法添加到线程池中ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), someStateObject);
}

someStateObject是DoWork的参数进行传入,然后开启线程。

2.SetMinThreads和SetMaxThreads

SetMinThreads和SetMaxThreads是线程池中最小线程数和最大线程数 


// 参数:// workerThreads:// 要由线程池根据需要创建的新的最小工作程序线程数。// completionPortThreads:// 要由线程池根据需要创建的新的最小空闲异步 I/O 线程数。// 返回结果:如果更改成功,则为 true;否则为 false。[SecuritySafeCritical]public static bool SetMinThreads(int workerThreads, int completionPortThreads);// 参数:// workerThreads:// 线程池中辅助线程的最大数目。// completionPortThreads:// 线程池中异步 I/O 线程的最大数目。// 返回结果:如果更改成功,则为 true;否则为 false。[SecuritySafeCritical]public static bool SetMaxThreads(int workerThreads, int completionPortThreads)例如:ThreadPool.SetMinThreads(1,1);ThreadPool.SetMaxThreads(5, 5);

3.ManualResetEvent用法

1.ManualResetEvent 调用一次Set()后将允许恢复所有被阻塞线程。需手动在调用WaitOne()之后调用Reset()重置信号量状态为非终止,然后再次调用WaitOne()的时候才能继续阻塞线程,反之则不阻塞

2.AutoResetEvent,调用一次Set()只能继续被阻塞的一个线程,多次调用Set()才行,但不需手动调用Reset();再次调用WaitOne()的时候又能阻塞线程,也是和前者的区别

3.两者单个实例均可阻塞一个或多个线程,在多个线程中调用 主线程 创建的 两者单个实例.WaitOne(),前提是两者实例必须是非终止状态

4.两者实例化构造参数解释

public AutoResetEvent(bool initialState);

true:设置终止状态。相当于调用了Set(),即首次不会被WaitOne()阻塞,下次执行WaitOne()才会被阻塞

false:设置非终止状态。遇到WaitOne()立即阻塞所在的一个或多个线程

具体参考一下文章:

C#学习(二十八)——ManualResetEvent的理解和使用-CSDN博客

三、ThreadPool代码

代码1:关于ManualResetEvent用法

using System;
using System.Threading;public class Example
{// mre is used to block and release threads manually. It is// created in the unsignaled state.private static ManualResetEvent mre = new ManualResetEvent(false);static void Main(){Console.WriteLine("\nStart 3 named threads that block on a ManualResetEvent:\n");//中文注释1:开启三个线程,每个线程开启后调用WaitOne()阻塞。for(int i = 0; i <= 2; i++){Thread t = new Thread(ThreadProc);t.Name = "Thread_" + i;t.Start();}Thread.Sleep(500);Console.WriteLine("\nWhen all three threads have started, press Enter to call Set()" +"\nto release all the threads.\n");Console.ReadLine();//中文注释2:只有当Set()后才会执行WaitOne()后的代码mre.Set();Thread.Sleep(500);Console.WriteLine("\nWhen a ManualResetEvent is signaled, threads that call WaitOne()" +"\ndo not block. Press Enter to show this.\n");Console.ReadLine();//中文注释3:继续再开两个线程,仍然调用WaitOne(),但是不会阻塞,会继续执行for(int i = 3; i <= 4; i++){Thread t = new Thread(ThreadProc);t.Name = "Thread_" + i;t.Start();}Thread.Sleep(500);Console.WriteLine("\nPress Enter to call Reset(), so that threads once again block" +"\nwhen they call WaitOne().\n");Console.ReadLine();//中文注释4:只有Reset()后,下面再开线程就会继续被阻塞mre.Reset();// Start a thread that waits on the ManualResetEvent.Thread t5 = new Thread(ThreadProc);t5.Name = "Thread_5";t5.Start();Thread.Sleep(500);Console.WriteLine("\nPress Enter to call Set() and conclude the demo.");Console.ReadLine();//中文注释5:再次Set(),就可以了mre.Set();// If you run this example in Visual Studio, uncomment the following line://Console.ReadLine();}private static void ThreadProc(){string name = Thread.CurrentThread.Name;Console.WriteLine(name + " starts and calls mre.WaitOne()");mre.WaitOne();Console.WriteLine(name + " ends.");}
}/* This example produces output similar to the following:Start 3 named threads that block on a ManualResetEvent:Thread_0 starts and calls mre.WaitOne()
Thread_1 starts and calls mre.WaitOne()
Thread_2 starts and calls mre.WaitOne()When all three threads have started, press Enter to call Set()
to release all the threads.Thread_2 ends.
Thread_0 ends.
Thread_1 ends.When a ManualResetEvent is signaled, threads that call WaitOne()
do not block. Press Enter to show this.Thread_3 starts and calls mre.WaitOne()
Thread_3 ends.
Thread_4 starts and calls mre.WaitOne()
Thread_4 ends.Press Enter to call Reset(), so that threads once again block
when they call WaitOne().Thread_5 starts and calls mre.WaitOne()Press Enter to call Set() and conclude the demo.Thread_5 ends.

代码2:


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;namespace ConsoleApplication1
{class Program{static void Main(string[] args){const int times = 10;  //开线程数ManualResetEvent[] mre = new ManualResetEvent[times];   //1、定义开线程数Random random = new Random();   //随机数Console.WriteLine("开始 {0} 任务", times);for (int i = 0; i < times; i++)   //2、循环这10个线程{mre[i] = new ManualResetEvent(false);  //3、初始化每个线程:设置false表示无信号,将使WaitOne阻塞也就是线程等待count c = new count(random.Next(1, 1000), mre[i]);   //借助类传参ThreadPool.QueueUserWorkItem(c.ThreadPoolCallback, i);   //4、为每个线程安排任务}WaitHandle.WaitAll(mre);    //6、让主线程等待所有线程完成(池中线程数不能多于64个)Console.WriteLine("所有线程完成!");Console.Read();}}class count{private int ramNum;   //存放随机数private ManualResetEvent threadSta;   //线程状态private int total;    //存放线程计算结果/// <summary>/// 传递数据/// </summary>/// <param name="ramnum">保存随机数</param>/// <param name="mre">线程状态</param>public count(int ramnum, ManualResetEvent mre){ramNum = ramnum;threadSta = mre;}/// <summary>/// 线程/// </summary>/// <param name="threadParam"></param>public void ThreadPoolCallback(Object threadParam){int threadIndex = (int)threadParam;Console.WriteLine("线程 {0} 启动", threadIndex);total = docount(ramNum);Console.WriteLine("线程执行结果: {0}", total);threadSta.Set();  //5、设置每个线程为有信号状态:通知WaitOne不再阻塞}/// <summary>/// 从0开始加到传过来数/// </summary>/// <param name="ramNum">传过来的数:产生的随机数</param>/// <returns>返回相加的结果</returns>public int docount(int ramNum){int sum = 0;for (int i = 0; i <= ramNum; i++){sum += i;}return sum;}}
}

参考文献:

C#中的线程池使用方法_c# 线程池-CSDN博客

C#多线程--线程池(ThreadPool)_c# 主线程和 线程池-CSDN博客

C#知识点讲解之ManualResetEvent类的使用-CSDN博客

C#线程池实例(多参)_c# 线程池多参数-CSDN博客

C#多线程和线程池_c#线程池和线程的区别-CSDN博客

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/101246.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Vue3中reactive, onMounted, ref,toRaw,conmpted 使用方法

import { reactive, onMounted, ref,toRaw,conmpted } from vue; vue3中 reactive &#xff0c;ref &#xff0c; toRaw&#xff0c;watch&#xff0c;conmpted 用法 toRaw 返回原响应式对象 用法&#xff1a; const rowList toRaw(row) reactive:ref: ref和reactive都是V…

快讯|Tubi 有 Rabbit AI 啦

在每月一期的 Tubi 快讯中&#xff0c;你将全面及时地获取 Tubi 最新发展动态&#xff0c;欢迎星标关注【比图科技】微信公众号&#xff0c;一起成长变强&#xff01; Tubi 推出 Rabbit AI 帮助用户找到喜欢的视频内容 Tubi 于今年九月底推出了 Rabbit AI&#xff0c;这是一项…

有效回收组分含量

声明 本文是学习GB-T 42944-2023 纸、纸板和纸制品 有效回收组分的测定. 而整理的学习笔记,分享出来希望更多人受益,如果存在侵权请及时联系我们 1 范围 本文件描述了纸、纸板和纸制品中有效回收组分的测定方法。 本文件适用于各种纸、纸板和纸制品&#xff0c;也适用于铝箔…

AndroidStudio报错:Plugin with id ‘kotlin-android‘ not found.

第一步 要在自己的项目的build.gradle的buildscript中添加ext.kotlin_version 1.3.72 第二步 然后在dependencies里添加classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 大体如下&#xff1a; buildscript {ext.kotlin_version 1.3.72r…

Qt如何在视频画面上新增车道线显示

在Qt中向视频画面上新增车道线显示通常需要以下步骤&#xff1a; 1.获取视频流或帧数据&#xff1a;首先&#xff0c;您需要获取视频流或视频帧的数据。您可以使用Qt的多媒体模块或其他第三方库来捕获视频流&#xff0c;或者从视频文件中读取帧数据。这将是您要在其上绘制车道…

【自动驾驶】PETR/PETRv2/StreamPETR论文分析

1.PETR PETR网络结构如下&#xff0c;主要包括image-backbone, 3D Coordinates Generator, 3D Position Encoder, transformer Decoder 1.1 Images Backbone 采用resnet 或者 vovNet,下面的x表示concatenate 1.2 3D Coordinates Generator 坐标生成跟lss类似&#xff0c;假…

如何对比github中不同commits的区别

有时候想要对比跨度几十个commits之前的代码区别&#xff0c;想直接使用github的用户界面。可以直接在官网操作。 示例 首先要创建一个旧commit的branch。进入该旧的commit&#xff0c;然后输入branch名字即可。 然后在项目网址后面加上compare即可对比旧的branch和新的bran…

【轻松玩转MacOS】故障排除篇

引言 在使用 MacOS 时&#xff0c;遇到故障是在所难免的。不要担心&#xff0c;这篇文章将为您提供一些常见的故障排除步骤&#xff0c;并介绍如何联系苹果的支持团队寻求帮助。让我们一起来看看吧&#xff01; 一、常见的故障排除步骤 1.1 网络连接问题 如果你发现你的Mac…

初识华为云数据库GaussDB for openGauss

01 前言 GaussDB是华为自主创新研发的分布式关系型数据库。该产品具备企业级复杂事务混合负载能力&#xff0c;同时支持分布式事务&#xff0c;同城跨AZ部署&#xff0c;数据0丢失&#xff0c;支持1000的扩展能力&#xff0c;PB级海量存储。同时拥有云上高可用&#xff0c;高可…

【postgresql】ERROR: integer out of range

查询文章都类似&#xff0c;只是类型没有对应上&#xff0c;根据实际情况处理。 前情 使用postgresql数据库数据库ID类型int4实体类代码private Long id; 异常 ### Cause: org.postgresql.util.PSQLException: ERROR: integer out of range ; ERROR: integer out of range;…

Go 语言切片扩容规则是扩容2倍?1.25倍?到底几倍

本次主要来聊聊关于切片的扩容是如何扩的&#xff0c;还请大佬们不吝赐教 切片&#xff0c;相信大家用了 Go 语言那么久这这种数据类型并不陌生&#xff0c;但是平日里聊到关于切片是如何扩容的&#xff0c;很多人可能会张口就来&#xff0c;切片扩容的时候&#xff0c;如果老…

centos 安装 percona-xtrabackup

一、yum安装 1.安装Percona yum存储库 yum install https://repo.percona.com/yum/percona-release-latest.noarch.rpm 2.启用Percona Server 8.0存储库 percona-release setup ps57 3.输出如下则安装成功 [rootlocalhost ~]# percona-release setup ps80 * Disabling all…

unity中绑定动画的行为系统

主要代码逻辑是创建一个action队列,当动画播放结束时就移除队头,执行后面的事件 public class Enemy : MonoBehaviour {public event Action E_AnimatorFin;//当动画播放完毕时public Action DefaultAction;//默认事件public Dictionary<Action, string> EventAnimator n…

基于 chinese-roberta-wwm-ext 微调训练中文命名实体识别任务

一、模型和数据集介绍 1.1 预训练模型 chinese-roberta-wwm-ext 是基于 RoBERTa 架构下开发&#xff0c;其中 wwm 代表 Whole Word Masking&#xff0c;即对整个词进行掩码处理&#xff0c;通过这种方式&#xff0c;模型能够更好地理解上下文和语义关联&#xff0c;提高中文文…

振弦传感器和振弦采集仪应用隧道安全监测的解决方案

振弦传感器和振弦采集仪应用隧道安全监测的解决方案 现代隧道越来越复杂&#xff0c;对于隧道安全的监测也变得越来越重要。振弦传感器和振弦采集仪已经成为了一种广泛应用的技术&#xff0c;用于隧道结构的监测和评估。它们可以提供更精确的测量结果&#xff0c;并且可以在实…

0基础学习VR全景平台篇 第104篇:720全景后期软件安装

上课&#xff01;全体起立~ 大家好&#xff0c;欢迎观看蛙色官方系列全景摄影课程&#xff01; 摄影进入数码时代&#xff0c;后期软件继承“暗房工艺”&#xff0c;成为摄影师表达内在情感的必备工具。 首先说明&#xff0c;全景摄影与平面摄影的一个显著的区别是全景图片需…

ChatGPT私有数据结合有什么效果?它难吗?

ChatGPT的出现可谓是惊艳了全世界&#xff0c;ChatGPT的问答能力通过了图灵测试&#xff0c;使其回答问题的方式与人类几乎无法区分。大家不甘于只在官方的对话页面问答&#xff0c;想利用 GPT 模型的自然语言能力结合私有数据开拓更多的应用场景。 | ChatGPT私有数据结合特点 …

滚珠螺母在工业机器人中的应用优势

工业机器人是广泛用于工业领域的多关节机械手或多自由度的机器装置&#xff0c;具有一定的自动性&#xff0c;可依靠自身的动力能源和控制能力实现各种工业加工制造功能。滚珠螺母作为工业机器人中的重要传动配件&#xff0c;在工业机器人的应用中有哪些优势呢&#xff1f; 1、…

SpringMVC修炼之旅(1)什么是SpringMVC

一、什么是MVC 1.1概述 MVC是模型(Model)、视图(View)、控制器(Controller)的简写&#xff0c;是一种软件设计规范。 是将业务逻辑、数据、显示分离的方法来组织代码。 MVC主要作用是降低了视图与业务逻辑间的双向偶合。 MVC不是一种设计模式&#xff0c;MVC是一种架构模式…

主从Reactor高并发服务器

文章目录 Reactor模型的典型分类单Reactor单线程单Reactor多线程多Reactor多线程本项目中实现的主从Reactor One Thread One Loop各模型的优点与缺点 项目分解Reactor服务器模块BufferSocketChannelEpollerTimerWheelEventLoopAnyConnectionAcceptorLoopThreadLoopThreadPoolTc…