【c#】线程Monitor.Wait和Monitor.Pulse使用

介绍

以一个简易版的数据库连接池的实现来说明一下
连接池的connection以队列来管理
getConnection的时候,如果队列中connection个数小于50,且暂时无可用的connection(个数为0或者peek看下头部需要先出那个元素还处于不可用状态),就新建连接并建立连接,开始一直新建到50个connection,就是_currentPoolSize =50
如果队列中connection个数大于等于50,且暂时无可用的connection(个数为0或者peek看下头部需要先出那个元素还处于不可用状态),就等着Monitor.Wait(_connectionPoolQueueLock)

returnConnection的时候,使用Monitor.Pulse(_connectionPoolQueueLock) 随机通知一个wait的线程可以继续getConnection了

using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using Mono.Data.Sqlite;namespace demo.unity.sqlite
{public class SQLiteConnectionManager{private Queue<Tuple<SqliteConnection, DateTime>> _connectionPoolQueue;private object _connectionPoolQueueLock = new object();private const int maxPoolSize = 50;private volatile bool _disposed;private int _currentPoolSize;private readonly System.Timers.Timer _cleanupTimer = new System.Timers.Timer(10 * 60 * 1000);public SQLiteConnectionManager(){_connectionPoolQueue = new Queue<Tuple<SqliteConnection, DateTime>>(maxPoolSize);_cleanupTimer.Elapsed += _cleanupTimerElapsed;_cleanupTimer.AutoReset = true;_cleanupTimer.Start();}private void _cleanupTimerElapsed(object sender, System.Timers.ElapsedEventArgs e){lock (_connectionPoolQueueLock){while (_connectionPoolQueue.Count > 0 && (DateTime.UtcNow - _connectionPoolQueue.Peek().Item2).TotalMinutes > 15){var tup = _connectionPoolQueue.Dequeue();tup.Item1.Dispose();_currentPoolSize--;}}}private SqliteConnection _createNewConnection(SqliteConnectionStringBuilder builder){var connection = new SqliteConnection(builder.ConnectionString);connection.Open();return connection;}public SqliteConnection getConnection(SqliteConnectionStringBuilder builder){lock (_connectionPoolQueueLock){// count == 0 or queue.peek no use connectionwhile (_connectionPoolQueue.Count == 0  || _connectionPoolQueue.Peek().Item1.State != ConnectionState.Open){if (_disposed){throw new ObjectDisposedException("The DB connection pool is is already disposed");}if (_currentPoolSize < maxPoolSize){// create and open connectionvar connection = _createNewConnection(builder);_connectionPoolQueue.Enqueue( new Tuple<SqliteConnection, DateTime>(connection, DateTime.UtcNow));_currentPoolSize++;}else{Monitor.Wait(_connectionPoolQueueLock);}}return _connectionPoolQueue.Dequeue().Item1;}}public void returnConnection(SqliteConnection connection){if (connection == null){return;}lock (_connectionPoolQueueLock){_connectionPoolQueue.Enqueue(new Tuple<SqliteConnection, DateTime>(connection, DateTime.UtcNow));Monitor.Pulse(_connectionPoolQueueLock);}}public void dispose(){lock (_connectionPoolQueueLock){_disposed = true;while (_connectionPoolQueue.Count > 0){var tup  = _connectionPoolQueue.Dequeue();tup.Item1?.Dispose();_currentPoolSize--;}// wake up any waiting threadsMonitor.PulseAll(_connectionPoolQueueLock);}_cleanupTimer.Stop();_cleanupTimer.Dispose();}}
}

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

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

相关文章

Dockerfile自定义容器

1、Dockerfile Dockerfile 是用于构建 Docker 镜像的文本文件&#xff0c;其中包含一系列的指令和配置&#xff0c;用于定义镜像的构建过程。通过 Dockerfile&#xff0c;你可以定义镜像的基础操作系统、依赖、环境设置、应用程序等信息&#xff0c;从而实现可复制、自动化的镜…

应用DeepSORT实现目标跟踪

在ByteTrack被提出之前&#xff0c;可以说DeepSORT是最好的目标跟踪算法之一。本文&#xff0c;我们就来应用这个算法实现目标跟踪。 DeepSORT的官方网址是https://github.com/nwojke/deep_sort。但在这里&#xff0c;我们不使用官方的代码&#xff0c;而使用第三方代码&#…

linux之date命令

date 命令用于 显示 或 设置系统的时间或日期。 格式&#xff1a;date [参数] [日期格式] 注意&#xff1a; date后面有一个空格&#xff0c;否则无法识别命令&#xff0c;shell对空格是很严格的。 1、Linux date命令参数 日期时间格式符号&#xff1a; %H  小时(以00-23来表示…

HRM人力资源管理系统源码

HRM人力资源管理系统源码 运行环境&#xff1a;PHP8.1或以上 MYSQL5.7或以上 php扩展要求 fileinfo imagemagick 功能介绍&#xff1a; 综合仪表板 它通过其综合仪表板提供了员工总数、工单和帐户余额的概览。 您可以轻松访问组织中的缺席者以及详细的公告和预定会议列…

股票杠杆交易平台排名:淘配网推荐的十大平台

在投资世界中&#xff0c;股票杠杆交易一直以其提供更高回报机会的吸引力而备受欢迎。随着市场的不断发展&#xff0c;出现了越来越多的股票杠杆交易平台。本文将为您介绍淘配网推荐的十大股票杠杆交易平台&#xff0c;并分析它们的特点。 富灯网 - 富灯网以其全面的杠杆产品和…

OpenCV C++ Look Up Table(查找表)

OpenCV C Look Up Table&#xff08;查找表&#xff09; 引言 在图像处理和计算机视觉中&#xff0c;查找表&#xff08;Look Up Table, LUT&#xff09;是一种非常高效和实用的方法&#xff0c;用于快速地映射或更改图像的颜色和像素值。LUT 能够极大地提高图像处理算法的执…

微信小程序:实现列表单选

效果 代码 wxml <view class"all"><view class"item_all" wx:for"{{info}}" wx:key"index"><view classposition {{item.checked?"checked_parameter":""}} data-id"{{item.employee_num}}…

20231008工作心得:sql

1.SQL语句里的if的嵌套使用 if(product A and brand_name B,C,if(product A and brand_name !B,D,product)) as product if&#xff08;A,B,C&#xff09;。SQL里if函数&#xff0c;如果条件A成立&#xff0c;就显示B的值&#xff0c;否则就显示C。 这个代码的意思的&#x…

一文读懂Base64

这几天在和第三方交互的时候&#xff0c;对方返回的数据是base64格式的数据&#xff0c;所以这两天又彻底捋了下Base64的来龙去脉。之前看过一篇文章说的非常好&#xff08;再找到给加上链接&#xff09;&#xff0c;我在这不详细说明了&#xff0c;只说转换过程。 还是使用中…

DiffusionDet:第一个用于物体检测的扩散模型(DiffusionDet: Diffusion Model for Object Detection)

提出了一种新的框架——DiffusionDet&#xff0c;它将目标检测定义为一个从有噪声的盒子到目标盒子的去噪扩散过程。在训练阶段&#xff0c;目标盒从真实值盒扩散到随机分布&#xff0c;模型学会了逆转这个噪声过程。 在推理中&#xff0c;该模型以渐进的方式将一组随机生成的框…

云计算:常用系统前端与后端框架

目录 一、理论 1.前端 2.后端 一、理论 1.前端 &#xff08;1&#xff09;JavaScript框架 JQuery.JS ZeptoJS(与jquery类似) SUI.Mobile Node.JS (服务端) angular.Js (模型&#xff0c;scope作用域&#xff0c;controller, 依赖注入&#xff0c;MVVM) :前端MVC . requir…

Uniapp 新手专用 抖音登录 获取用户头像、名称、openid、unionid、anonymous_openid、session_key

TC-dylogin 一定请选择 源码授权版 教程 第一步 将代码拷贝至您所需要的页面 该代码位置&#xff1a;pages/index.vue 第二步 修改appid和secret 第三步 获取appid和secret 获取appid和secret链接 注意事项 为了安全&#xff0c;我将默认的自己的appid和secret在云函数中删…

图片调色盘

图片预览 配置安装 Color-Thief 安装包使用文档 yarn add colorthief -S // npm install colorthief --save代码 <template><div class"img-thief"><div class"container"><div class"thief-item" v-for"(item, in…

【Spring】Spring MVC 程序开发

Spring MVC 程序开发 一. 什么是 Spring MVC1. MVC2. Spring、Spring Boot 与 Spring MVC 二. 创建 Spring MVC 项目1. 创建项目2. 用户和程序的映射3. 获取用户请求参数①. 获取单个参数②. 获取多个参数③. 传递对象④. 后端参数重命名&#xff08;后端参数映射&#xff09;R…

【初识Jmeter】【接口自动化】

jmeter的使用笔记1 Jmeter介绍与下载安装介绍安装配置配置与扩展组件 jmeter的使用基本功能元素登陆请求与提取cookie其他请求接口关联Cookie-响应成功聚合报告查看 Jmeter介绍与下载安装 介绍 jmeter是apache公司基于java开发的一款开源压力测试工具&#xff0c;体积小&…

opencv实现抠图,图像拼接,图像融合

在OpenCV中&#xff0c;你可以使用图像拼接、抠图和将图像的一部分放在另一张图片的指定位置。以下是示例代码&#xff0c;演示如何执行这些操作&#xff1a; 图像拼接 要将两张图像拼接在一起&#xff0c;你可以使用 cv::hconcat&#xff08;水平拼接&#xff09;和 cv::vco…

spring boot整合 Redis

Spring Boot 整合 Redis pom.xml依赖&#xff1a; <!-- redis依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><gro…

基于卷积神经网络的图像识别-案例实施1

案例描述 学习如何搭建CNN卷积神经网络&#xff0c;训练cifar-10数据&#xff0c;识别图片中的内容。 案例分析 cifar-10是由Hinton的学生Alex Krizhevsky和Ilya Sutskever整理的一个用于识别普适物体的小型数据集。一共包含 10个类别的 RGB 彩色图 片&#xff1a;飞机&…

节日灯饰灯串灯出口欧洲CE认证检测

灯串&#xff08;灯带&#xff09;&#xff0c;这个产品的形状就象一根带子一样&#xff0c;再加上产品的主要原件就是LED&#xff0c;因此叫做灯串或者灯带。2022年&#xff0c;我国灯具及相关配件产品出口总额超过460亿美元。其中北美是最大的出口市场。其次是欧洲市场&#…

【网络安全---XSS漏洞(1)】XSS漏洞原理,产生原因,以及XSS漏洞的分类。附带案例和payload让你快速学习XSS漏洞

以pikachu靶场为例子进行讲解&#xff0c;pikachu靶场的搭建请参考以下博客&#xff1b; 【网路安全 --- pikachu靶场安装】超详细的pikachu靶场安装教程&#xff08;提供靶场代码及工具&#xff09;_网络安全_Aini的博客-CSDN博客【网路安全 --- pikachu靶场安装】超详细的pi…