From 3fc1302cfbf315956040f5592442c4edcc593ab4 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sat, 21 Dec 2024 20:35:40 +0800 Subject: [PATCH 01/52] style: remove unused using --- TYLDDB/TYLDDB.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/TYLDDB/TYLDDB.cs b/TYLDDB/TYLDDB.cs index a8c6986..569a5c9 100644 --- a/TYLDDB/TYLDDB.cs +++ b/TYLDDB/TYLDDB.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using System.Threading.Tasks; using TYLDDB.Basic; using TYLDDB.Utils; From e405fca5339d85ab39f083076321be3b29fc154e Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sat, 21 Dec 2024 20:36:07 +0800 Subject: [PATCH 02/52] docs: change some comments --- TYLDDB.Test/Program.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/TYLDDB.Test/Program.cs b/TYLDDB.Test/Program.cs index 942e036..d2f6cee 100644 --- a/TYLDDB.Test/Program.cs +++ b/TYLDDB.Test/Program.cs @@ -5,7 +5,7 @@ LDDB lddb = new LDDB(); ///////////////////////////////////////////////////////////////////////////////////////////////////////// 读取文件 -HighPrecisionTimer readDbTimer = new(); // 从发起读取文件指令到成功读取的总时间 +HighPrecisionTimer readDbTimer = new(); // 从发起读取文件到成功读取的总时间 readDbTimer.Start(); lddb.FilePath = "./example.lddb"; lddb.ReadingFile(); @@ -13,7 +13,7 @@ WriteTime("从发起读取文件指令到成功读取的总时间为: ", readDbTimer.ElapsedMilliseconds()); ///////////////////////////////////////////////////////////////////////////////////////////////////////// 读取数据库 -HighPrecisionTimer loadDbTimer = new(); // 从发起读取数据库指令到成功返回读取内容的总时间 +HighPrecisionTimer loadDbTimer = new(); // 从发起读取数据库到成功返回读取内容的总时间 loadDbTimer.Start(); lddb.LoadDatabase("database1"); Console.WriteLine(lddb.GetLoadingDatabaseContent()); // 输出database1内容 @@ -21,7 +21,7 @@ WriteTime("从发起读取数据库指令到成功返回读取内容的总时间为: ", loadDbTimer.ElapsedMilliseconds()); ///////////////////////////////////////////////////////////////////////////////////////////////////////// 获取所有数据库名称 -HighPrecisionTimer readAllDbNameTimer = new(); // 从发起读取数据库指令到成功返回读取内容的总时间 +HighPrecisionTimer readAllDbNameTimer = new(); // 从发起读取数据库名称到成功返回读取内容的总时间 readAllDbNameTimer.Start(); lddb.ReadAllDatabaseName(); readAllDbNameTimer.Stop(); @@ -32,7 +32,7 @@ Console.WriteLine(dbName); } } -WriteTime("从发起读取数据库指令到成功返回读取内容的总时间为: ", readAllDbNameTimer.ElapsedMilliseconds()); +WriteTime("从发起读取数据库名称到成功返回读取内容的总时间为: ", readAllDbNameTimer.ElapsedMilliseconds()); From f0f43e886163ad35029f1c007087ae8aaaf8558e Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sun, 22 Dec 2024 13:33:11 +0800 Subject: [PATCH 03/52] docs: add "How To Use" file --- TYLDDB/How-To-Use.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 TYLDDB/How-To-Use.md diff --git a/TYLDDB/How-To-Use.md b/TYLDDB/How-To-Use.md new file mode 100644 index 0000000..ebee15e --- /dev/null +++ b/TYLDDB/How-To-Use.md @@ -0,0 +1,43 @@ +# How to use TYLDDB + +## Basic content + +### Read database + +#### Instantiate the LDDB class + +```c# +LDDB lddb = new LDDB(); +``` + +If you are using a higher version .NET, you can also write a little simpler. + +```c# +LDDB lddb = new(); +``` + +#### Read file + +```c# +lddb.FilePath = "./example.lddb"; +lddb.ReadingFile(); +``` + +The contents of the file are then loaded into memory. + +#### Select the database to read + +```c# +lddb.LoadDatabase("database1"); +``` + +This allows you to select the contents of the database for the next operation + +If you want to get all the contents of this database, you can use `lddb.GetLoadingDatabaseContent()` , which returns a string. + +#### Gets all database names + +```c# +lddb.ReadAllDatabaseName(); +``` + From 9a0aa6c1268158754bb0ee81593a7dcd1005186c Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 23 Dec 2024 21:48:49 +0800 Subject: [PATCH 04/52] =?UTF-8?q?=E5=86=99=E4=B8=89=E4=B8=AA=E6=96=B0?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E7=94=A8=E4=BA=8E=E8=AF=BB=E5=8F=96=E4=B8=8D?= =?UTF-8?q?=E5=90=8C=E5=A4=A7=E5=B0=8F=E7=9A=84=E6=96=87=E4=BB=B6=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/Utils/ReadFile.cs | 42 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/TYLDDB/Utils/ReadFile.cs b/TYLDDB/Utils/ReadFile.cs index ebd4d55..8dc7b88 100644 --- a/TYLDDB/Utils/ReadFile.cs +++ b/TYLDDB/Utils/ReadFile.cs @@ -22,4 +22,46 @@ public static string ReadTylddbFile(string filePath) } } } +internal class NewReader +{ +public static string ReadFile(string fPath) +{return null;} +public static string ReadSmallFile(string path) +{return File.ReadAllText(path);} +public static string ReadMediumFile(string filePath) + { + // 使用 FileStream 和 BufferedStream 进行高效读取 + using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) + using (BufferedStream bs = new BufferedStream(fs)) + { + // 使用 MemoryStream 来动态存储文件内容 + using (MemoryStream ms = new MemoryStream()) + { + byte[] buffer = new byte[8192]; // 缓冲区大小 + int bytesRead; + + // 读取文件并将其内容写入 MemoryStream + while ((bytesRead = bs.Read(buffer, 0, buffer.Length)) > 0) + { + ms.Write(buffer, 0, bytesRead); + } + + // 返回完整文件内容的字符串 + return Encoding.UTF8.GetString(ms.ToArray()); + } + } + } +public static string ReadLargeFile(string filePath) + { + using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(filePath, FileMode.Open)) + { + using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) + { + byte[] buffer = new byte[accessor.Capacity]; + accessor.ReadArray(0, buffer, 0, (int)accessor.Capacity); + return Encoding.UTF8.GetString(buffer); + } + } + } +} } From 21800da092a0c61863f88f5ad000066531cee06f Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 23 Dec 2024 21:50:13 +0800 Subject: [PATCH 05/52] =?UTF-8?q?=E7=BB=9F=E4=B8=80=E4=BC=A0=E5=8F=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/Utils/ReadFile.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/TYLDDB/Utils/ReadFile.cs b/TYLDDB/Utils/ReadFile.cs index 8dc7b88..5cc4731 100644 --- a/TYLDDB/Utils/ReadFile.cs +++ b/TYLDDB/Utils/ReadFile.cs @@ -24,10 +24,10 @@ public static string ReadTylddbFile(string filePath) } internal class NewReader { -public static string ReadFile(string fPath) +public static string ReadFile(string filePath) {return null;} -public static string ReadSmallFile(string path) -{return File.ReadAllText(path);} +public static string ReadSmallFile(string filePath) +{return File.ReadAllText(filePath);} public static string ReadMediumFile(string filePath) { // 使用 FileStream 和 BufferedStream 进行高效读取 From 5cb8fe1ab1bb6a5f434757008c6ce566a969f15d Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 23 Dec 2024 21:55:14 +0800 Subject: [PATCH 06/52] =?UTF-8?q?=E6=89=A9=E5=A4=A7=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/Utils/ReadFile.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TYLDDB/Utils/ReadFile.cs b/TYLDDB/Utils/ReadFile.cs index 5cc4731..7807120 100644 --- a/TYLDDB/Utils/ReadFile.cs +++ b/TYLDDB/Utils/ReadFile.cs @@ -37,7 +37,7 @@ public static string ReadMediumFile(string filePath) // 使用 MemoryStream 来动态存储文件内容 using (MemoryStream ms = new MemoryStream()) { - byte[] buffer = new byte[8192]; // 缓冲区大小 + byte[] buffer = new byte[65536]; // 缓冲区大小 int bytesRead; // 读取文件并将其内容写入 MemoryStream From fa35dad15527339ece932bfc53692a3ceafa3960 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 23 Dec 2024 22:03:46 +0800 Subject: [PATCH 07/52] =?UTF-8?q?=E5=8A=A0=E5=85=A5=E8=87=AA=E5=8A=A8readf?= =?UTF-8?q?ile=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/Utils/ReadFile.cs | 52 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/TYLDDB/Utils/ReadFile.cs b/TYLDDB/Utils/ReadFile.cs index 7807120..f27479d 100644 --- a/TYLDDB/Utils/ReadFile.cs +++ b/TYLDDB/Utils/ReadFile.cs @@ -25,7 +25,57 @@ public static string ReadTylddbFile(string filePath) internal class NewReader { public static string ReadFile(string filePath) -{return null;} +{ +// 获取文件信息 + FileInfo fileInfo = new FileInfo(filePath); + + // 获取文件大小 (单位字节) + long fileSize = fileInfo.Length; + + // 根据文件大小区间进行不同的处理 + if (fileSize < 1 * 1024 * 1024) // 小于 1MB + { + ReadSmallFile(filePath); + } + else if (fileSize < 15 * 1024 * 1024) // 小于 15MB + { + ReadMediumFile(filePath); + } + else + { + Console.WriteLine("文件较大 (> 10MB 且 <= 25MB),使用缓冲读取方式处理。"); + ReadLargeFile(filePath); + } +} +// 定义委托类型,表示文件处理的方式 + private delegate void FileProcessingStrategy(string filePath); + + // 使用一个字典来映射文件大小区间到处理方法 + private static readonly Dictionary<(long, long), FileProcessingStrategy> FileProcessingStrategies + = new Dictionary<(long, long), FileProcessingStrategy> + { + { (0, 1 * 1024 * 1024), ReadSmallFile }, // 小于 1MB + { (1 * 1024 * 1024, 15 * 1024 * 1024), ReadMediumFile }, // 1MB 到 15MB + { (15 * 1024 * 1024, long.MaxValue), ReadLargeFile } // 大于 15MB + }; + + public static void ReadFilePlus(string filePath) + { + // 获取文件信息 + FileInfo fileInfo = new FileInfo(filePath); + long fileSize = fileInfo.Length; + + // 根据文件大小选择合适的处理方法 + foreach (var entry in FileProcessingStrategies) + { + var (minSize, maxSize) = entry.Key; + if (fileSize > minSize && fileSize <= maxSize) + { + entry.Value(filePath); // 调用相应的处理策略 + break; + } + } + } public static string ReadSmallFile(string filePath) {return File.ReadAllText(filePath);} public static string ReadMediumFile(string filePath) From 9750411a4af83646f03ca026e2f6b86c9b9a96a5 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Tue, 24 Dec 2024 15:46:59 +0800 Subject: [PATCH 08/52] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=97=A0=E7=94=A8?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/Basic/Exception.cs | 43 --------------------------------------- 1 file changed, 43 deletions(-) diff --git a/TYLDDB/Basic/Exception.cs b/TYLDDB/Basic/Exception.cs index 5a20261..c354060 100644 --- a/TYLDDB/Basic/Exception.cs +++ b/TYLDDB/Basic/Exception.cs @@ -2,48 +2,6 @@ namespace TYLDDB.Basic { -#if NET8_0_OR_GREATER - /// - /// The main error module, most of them use this
- /// 主要的错误模块,大部分都使用这个 - ///
- public class TylddbException(string message) : Exception(message) { } - /// - /// File opening failure
- /// 文件打开失败 - ///
- public class FileOpenFailException(string message) : TylddbException(message) { } - /// - /// File read failure
- /// 文件读取失败 - ///
- public class FileReadingFailException(string message) : TylddbException(message) { } - /// - /// File not found
- /// 文件未找到 - ///
- public class FileNotFoundException(string message) : TylddbException(message) { } - /// - /// The file path is null or space
- /// 文件路径为null或空白 - ///
- public class FilePathIsNullOrWhiteSpace(string message) : TylddbException(message) { } - /// - /// Incorrect or invalid data
- /// 错误或无效的数据 - ///
- public class InvalidDataException(string message) : TylddbException(message) { } - /// - /// Database not found
- /// 未找到数据库 - ///
- public class DatabaseNotFoundException(string message) : TylddbException(message) { } - /// - /// Description Failed to obtain the database content
- /// 数据库内容获取失败 - ///
- public class GetDatabaseContentErrorException(string message) : TylddbException(message) { } -#else /// /// The main error module, most of them use this
/// 主要的错误模块,大部分都使用这个 @@ -140,5 +98,4 @@ public class GetDatabaseContentErrorException : TylddbException ///
public GetDatabaseContentErrorException(string message) : base(message) { } } -#endif } From ecc02915f1983c11015597205365a49069620b4b Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Tue, 24 Dec 2024 15:47:11 +0800 Subject: [PATCH 09/52] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E5=AF=B9=E6=97=A7?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E7=9A=84=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index 5b2f837..55ebde2 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -1,7 +1,7 @@  - netstandard1.6;netstandard2.0;netstandard2.1;net6.0;net8.0;net9.0 + netstandard2.0;netstandard2.1;net6.0;net8.0;net9.0 True TTYPDB.NET 1.0.0-beta.1 From c8e9a4d58bbfda61a614494cef71363c1a7e828a Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Tue, 24 Dec 2024 16:24:09 +0800 Subject: [PATCH 10/52] =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/Utils/ReadFile.cs | 244 ++++++++++++++++++++++++++++----------- 1 file changed, 175 insertions(+), 69 deletions(-) diff --git a/TYLDDB/Utils/ReadFile.cs b/TYLDDB/Utils/ReadFile.cs index f27479d..4695455 100644 --- a/TYLDDB/Utils/ReadFile.cs +++ b/TYLDDB/Utils/ReadFile.cs @@ -1,10 +1,22 @@ using System.IO; +using System.Text; using TYLDDB.Basic; namespace TYLDDB.Utils { - internal class ReadFile + /// + /// A struct used to read a file
+ /// 用于读取文件的结构体 + ///
+ public struct ReadFile { + /// + /// The earliest reading method based on FileStream + SreamReader.
+ /// 最早的基于 FileStream + SreamReader 的读取方法。 + ///
+ /// File path
文件路径 + /// File content
文件内容
+ /// public static string ReadTylddbFile(string filePath) { try @@ -21,97 +33,191 @@ public static string ReadTylddbFile(string filePath) throw new FileReadingFailException($"Error reading file: {ex.Message}"); } } - } -internal class NewReader -{ -public static string ReadFile(string filePath) -{ -// 获取文件信息 - FileInfo fileInfo = new FileInfo(filePath); - - // 获取文件大小 (单位字节) - long fileSize = fileInfo.Length; - // 根据文件大小区间进行不同的处理 - if (fileSize < 1 * 1024 * 1024) // 小于 1MB + /// + /// Select the desired method based on the file size
+ /// 根据文件大小选择所需的方法 + /// <1MB + /// 1MB~10MB + /// 10MB~15MB + /// 15MB~20MB + /// 20MB~30MB + /// >30MB + ///
+ /// File path
文件路径 + public static string ReadFileAuto(string filePath) { - ReadSmallFile(filePath); + // 获取文件信息 + FileInfo fileInfo = new FileInfo(filePath); + + // 获取文件大小 (单位字节) + long fileSize = fileInfo.Length; + + // 根据文件大小区间进行不同的处理 + if (fileSize < 1 * 1024 * 1024) // 小于 1MB + { + return ReadSmallFile(filePath); + } + else if (fileSize < 10 * 1024 * 1024) // 小于 10MB + { + return ReadMediumFile(filePath); + } + else if(fileSize < 15 * 1024 * 1024) // 小于 15MB + { + return ReadLargeFile_8(filePath); + } + else if(fileSize < 20 * 1024 * 1024) // 小于 20MB + { + return ReadLargeFile_64(filePath); + } + else if (fileSize < 30 * 1024 * 1024) // 小于 30MB + { + return ReadLargeFile_128(filePath); + } + else // 大于 30MB + { + return ReadVeryLargeFile(filePath); + } } - else if (fileSize < 15 * 1024 * 1024) // 小于 15MB + + /// + /// Read small file.
+ /// 读取小文件。 + ///
+ /// File path
文件路径 + /// File content
文件内容
+ public static string ReadSmallFile(string filePath) => File.ReadAllText(filePath); + + /// + /// Read medium file.
+ /// 读取中等大小文件。 + ///
+ /// File path
文件路径 + /// File content
文件内容
+ public static string ReadMediumFile(string filePath) { - ReadMediumFile(filePath); + // 使用 FileStream 和 BufferedStream 进行高效读取 + StringBuilder fileContent = new StringBuilder(); // 用来存储文件内容 + + using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) + using (BufferedStream bs = new BufferedStream(fs)) + using (StreamReader reader = new StreamReader(bs, Encoding.UTF8)) + { + string line; + while ((line = reader.ReadLine()) != null) + { + // 将每一行的内容追加到 fileContent + fileContent.AppendLine(line); + } + } + + return fileContent.ToString(); // 返回文件的所有内容 } - else + + /// + /// Read large file.(8KB buffer)
+ /// 读取大文件。(8KB缓冲区) + ///
+ /// File path
文件路径 + /// File content
文件内容
+ public static string ReadLargeFile_8(string filePath) { - Console.WriteLine("文件较大 (> 10MB 且 <= 25MB),使用缓冲读取方式处理。"); - ReadLargeFile(filePath); - } -} -// 定义委托类型,表示文件处理的方式 - private delegate void FileProcessingStrategy(string filePath); + // 这里采用分块读取文件的方式,避免一次性加载大文件 + const int bufferSize = 8192; // 8 KB缓冲区 + byte[] buffer = new byte[bufferSize]; + StringBuilder fileContent = new StringBuilder(); - // 使用一个字典来映射文件大小区间到处理方法 - private static readonly Dictionary<(long, long), FileProcessingStrategy> FileProcessingStrategies - = new Dictionary<(long, long), FileProcessingStrategy> - { - { (0, 1 * 1024 * 1024), ReadSmallFile }, // 小于 1MB - { (1 * 1024 * 1024, 15 * 1024 * 1024), ReadMediumFile }, // 1MB 到 15MB - { (15 * 1024 * 1024, long.MaxValue), ReadLargeFile } // 大于 15MB - }; + using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) + { + int bytesRead; + while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) + { + // 将每一块数据转换成字符串并累积到 fileContent 中 + string chunkContent = Encoding.UTF8.GetString(buffer, 0, bytesRead); + fileContent.Append(chunkContent); + } + } - public static void ReadFilePlus(string filePath) - { - // 获取文件信息 - FileInfo fileInfo = new FileInfo(filePath); - long fileSize = fileInfo.Length; + // 返回文件的全部内容 + return fileContent.ToString(); + } - // 根据文件大小选择合适的处理方法 - foreach (var entry in FileProcessingStrategies) + /// + /// Read large file.(64KB buffer)
+ /// 读取大文件。(64KB缓冲区) + ///
+ /// File path
文件路径 + /// File content
文件内容
+ public static string ReadLargeFile_64(string filePath) { - var (minSize, maxSize) = entry.Key; - if (fileSize > minSize && fileSize <= maxSize) + // 这里采用分块读取文件的方式,避免一次性加载大文件 + const int bufferSize = 65536; // 64 KB缓冲区 + byte[] buffer = new byte[bufferSize]; + StringBuilder fileContent = new StringBuilder(); + + using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { - entry.Value(filePath); // 调用相应的处理策略 - break; + int bytesRead; + while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) + { + // 将每一块数据转换成字符串并累积到 fileContent 中 + string chunkContent = Encoding.UTF8.GetString(buffer, 0, bytesRead); + fileContent.Append(chunkContent); + } } + + // 返回文件的全部内容 + return fileContent.ToString(); } - } -public static string ReadSmallFile(string filePath) -{return File.ReadAllText(filePath);} -public static string ReadMediumFile(string filePath) - { - // 使用 FileStream 和 BufferedStream 进行高效读取 - using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) - using (BufferedStream bs = new BufferedStream(fs)) + + /// + /// Read large file.(128KB buffer)
+ /// 读取大文件。(128KB缓冲区) + ///
+ /// File path
文件路径 + /// File content
文件内容
+ public static string ReadLargeFile_128(string filePath) { - // 使用 MemoryStream 来动态存储文件内容 - using (MemoryStream ms = new MemoryStream()) + // 这里采用分块读取文件的方式,避免一次性加载大文件 + const int bufferSize = 131072; // 128 KB缓冲区 + byte[] buffer = new byte[bufferSize]; + StringBuilder fileContent = new StringBuilder(); + + using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { - byte[] buffer = new byte[65536]; // 缓冲区大小 int bytesRead; - - // 读取文件并将其内容写入 MemoryStream - while ((bytesRead = bs.Read(buffer, 0, buffer.Length)) > 0) + while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) { - ms.Write(buffer, 0, bytesRead); + // 将每一块数据转换成字符串并累积到 fileContent 中 + string chunkContent = Encoding.UTF8.GetString(buffer, 0, bytesRead); + fileContent.Append(chunkContent); } - - // 返回完整文件内容的字符串 - return Encoding.UTF8.GetString(ms.ToArray()); } + + // 返回文件的全部内容 + return fileContent.ToString(); } - } -public static string ReadLargeFile(string filePath) - { - using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(filePath, FileMode.Open)) + + // 使用 MemoryMappedFile 读取非常大的文件 + /// + /// Read very large file.(Based on MemoryMappedFile)
+ /// 读取很大的文件。(基于MemoryMappedFile) + ///
+ /// File path
文件路径 + /// File content
文件内容
+ public static string ReadVeryLargeFile(string filePath) { - using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) + using (System.IO.MemoryMappedFiles.MemoryMappedFile mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(filePath, FileMode.Open)) { - byte[] buffer = new byte[accessor.Capacity]; - accessor.ReadArray(0, buffer, 0, (int)accessor.Capacity); - return Encoding.UTF8.GetString(buffer); + using (System.IO.MemoryMappedFiles.MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) + { + long length = accessor.Capacity; + byte[] buffer = new byte[length]; + accessor.ReadArray(0, buffer, 0, (int)length); + string content = Encoding.UTF8.GetString(buffer); + return content; + } } } } } -} From 692f4090e9b84b785ae85a8eabbd9cec93a833d1 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Tue, 24 Dec 2024 16:48:03 +0800 Subject: [PATCH 11/52] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB.Test/Program.cs | 51 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/TYLDDB.Test/Program.cs b/TYLDDB.Test/Program.cs index d2f6cee..534ec1a 100644 --- a/TYLDDB.Test/Program.cs +++ b/TYLDDB.Test/Program.cs @@ -1,5 +1,10 @@ using TYLDDB; using TYLDDB.Test; +using TYLDDB.Utils; + +string dbFilePath = "./example.lddb"; + +ReadFileMethodTest(); ///////////////////////////////////////////////////////////////////////////////////////////////////////// 实例化 LDDB lddb = new LDDB(); @@ -7,7 +12,7 @@ ///////////////////////////////////////////////////////////////////////////////////////////////////////// 读取文件 HighPrecisionTimer readDbTimer = new(); // 从发起读取文件到成功读取的总时间 readDbTimer.Start(); -lddb.FilePath = "./example.lddb"; +lddb.FilePath = dbFilePath; lddb.ReadingFile(); readDbTimer.Stop(); WriteTime("从发起读取文件指令到成功读取的总时间为: ", readDbTimer.ElapsedMilliseconds()); @@ -50,9 +55,49 @@ Console.ReadLine(); +////////////////////////////////////////////////////////////////////////////////////////////////////////// Test Method - - +void ReadFileMethodTest() +{ + HighPrecisionTimer readSmallFileFuncTime = new(); + HighPrecisionTimer readMediumFileFuncTime = new(); + HighPrecisionTimer readLarge8FileFuncTime = new(); + HighPrecisionTimer readLarge64FileFuncTime = new(); + HighPrecisionTimer readLarge128FileFuncTime = new(); + HighPrecisionTimer readVeryLargeFileFuncTime = new(); + readSmallFileFuncTime.Start(); + ReadFile.ReadSmallFile(dbFilePath); + readSmallFileFuncTime.Stop(); + readMediumFileFuncTime.Start(); + ReadFile.ReadMediumFile(dbFilePath); + readMediumFileFuncTime.Stop(); + readLarge8FileFuncTime.Start(); + ReadFile.ReadLargeFile_8(dbFilePath); + readLarge8FileFuncTime.Stop(); + readLarge64FileFuncTime.Start(); + ReadFile.ReadLargeFile_64(dbFilePath); + readLarge64FileFuncTime.Stop(); + readLarge128FileFuncTime.Start(); + ReadFile.ReadLargeFile_128(dbFilePath); + readLarge128FileFuncTime.Stop(); + readVeryLargeFileFuncTime.Start(); + ReadFile.ReadVeryLargeFile(dbFilePath); + readVeryLargeFileFuncTime.Stop(); + Console.WriteLine("不同读取文件的方法测试:"); + Console.WriteLine($"小文件读取:{readSmallFileFuncTime.ElapsedMilliseconds()}ms"); + Console.WriteLine($"中文件读取:{readMediumFileFuncTime.ElapsedMilliseconds()}ms"); + Console.WriteLine($"大文件读取8kb:{readLarge8FileFuncTime.ElapsedMilliseconds()}ms"); + Console.WriteLine($"大文件读取64kb:{readLarge64FileFuncTime.ElapsedMilliseconds()}ms"); + Console.WriteLine($"大文件读取256kb:{readLarge128FileFuncTime.ElapsedMilliseconds()}ms"); + Console.WriteLine($"特大文件读取:{readVeryLargeFileFuncTime.ElapsedMilliseconds()}ms"); + + // 获取文件信息 + FileInfo fileInfo = new FileInfo(dbFilePath); + // 获取文件大小 (单位字节) + long fileSize = fileInfo.Length; + + Console.WriteLine("使用的测试文件大小为:" + fileSize / 1024); +} ///////////////////////////////////////////////////////////////////////////////////////////////////////// 工具 static void WriteTime(string what, double time) From 41b856e4902f007394d47783f0fc2b8ef0f6cd7f Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Tue, 24 Dec 2024 16:49:10 +0800 Subject: [PATCH 12/52] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=97=A0=E6=B3=95?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E7=9A=84=E6=B5=8B=E8=AF=95=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB.Test/Program.cs | 45 ------------------------------------------ 1 file changed, 45 deletions(-) diff --git a/TYLDDB.Test/Program.cs b/TYLDDB.Test/Program.cs index 534ec1a..289cb0e 100644 --- a/TYLDDB.Test/Program.cs +++ b/TYLDDB.Test/Program.cs @@ -1,11 +1,8 @@ using TYLDDB; using TYLDDB.Test; -using TYLDDB.Utils; string dbFilePath = "./example.lddb"; -ReadFileMethodTest(); - ///////////////////////////////////////////////////////////////////////////////////////////////////////// 实例化 LDDB lddb = new LDDB(); @@ -57,48 +54,6 @@ ////////////////////////////////////////////////////////////////////////////////////////////////////////// Test Method -void ReadFileMethodTest() -{ - HighPrecisionTimer readSmallFileFuncTime = new(); - HighPrecisionTimer readMediumFileFuncTime = new(); - HighPrecisionTimer readLarge8FileFuncTime = new(); - HighPrecisionTimer readLarge64FileFuncTime = new(); - HighPrecisionTimer readLarge128FileFuncTime = new(); - HighPrecisionTimer readVeryLargeFileFuncTime = new(); - readSmallFileFuncTime.Start(); - ReadFile.ReadSmallFile(dbFilePath); - readSmallFileFuncTime.Stop(); - readMediumFileFuncTime.Start(); - ReadFile.ReadMediumFile(dbFilePath); - readMediumFileFuncTime.Stop(); - readLarge8FileFuncTime.Start(); - ReadFile.ReadLargeFile_8(dbFilePath); - readLarge8FileFuncTime.Stop(); - readLarge64FileFuncTime.Start(); - ReadFile.ReadLargeFile_64(dbFilePath); - readLarge64FileFuncTime.Stop(); - readLarge128FileFuncTime.Start(); - ReadFile.ReadLargeFile_128(dbFilePath); - readLarge128FileFuncTime.Stop(); - readVeryLargeFileFuncTime.Start(); - ReadFile.ReadVeryLargeFile(dbFilePath); - readVeryLargeFileFuncTime.Stop(); - Console.WriteLine("不同读取文件的方法测试:"); - Console.WriteLine($"小文件读取:{readSmallFileFuncTime.ElapsedMilliseconds()}ms"); - Console.WriteLine($"中文件读取:{readMediumFileFuncTime.ElapsedMilliseconds()}ms"); - Console.WriteLine($"大文件读取8kb:{readLarge8FileFuncTime.ElapsedMilliseconds()}ms"); - Console.WriteLine($"大文件读取64kb:{readLarge64FileFuncTime.ElapsedMilliseconds()}ms"); - Console.WriteLine($"大文件读取256kb:{readLarge128FileFuncTime.ElapsedMilliseconds()}ms"); - Console.WriteLine($"特大文件读取:{readVeryLargeFileFuncTime.ElapsedMilliseconds()}ms"); - - // 获取文件信息 - FileInfo fileInfo = new FileInfo(dbFilePath); - // 获取文件大小 (单位字节) - long fileSize = fileInfo.Length; - - Console.WriteLine("使用的测试文件大小为:" + fileSize / 1024); -} - ///////////////////////////////////////////////////////////////////////////////////////////////////////// 工具 static void WriteTime(string what, double time) { From 097b1ef7737fdeeb162826e73be45a86a8bc43a5 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Tue, 24 Dec 2024 16:49:29 +0800 Subject: [PATCH 13/52] =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.cs | 2 +- TYLDDB/Utils/ReadFile.cs | 190 +-------------------------------------- 2 files changed, 5 insertions(+), 187 deletions(-) diff --git a/TYLDDB/TYLDDB.cs b/TYLDDB/TYLDDB.cs index 569a5c9..7741e03 100644 --- a/TYLDDB/TYLDDB.cs +++ b/TYLDDB/TYLDDB.cs @@ -61,7 +61,7 @@ private static void ValidateFilePath(string path) /// public void ReadingFile() { - _fileContent = ReadFile.ReadTylddbFile(FilePath); + _fileContent = Reader.ReadFile(FilePath); _isRead = true; } diff --git a/TYLDDB/Utils/ReadFile.cs b/TYLDDB/Utils/ReadFile.cs index 4695455..31ecbe3 100644 --- a/TYLDDB/Utils/ReadFile.cs +++ b/TYLDDB/Utils/ReadFile.cs @@ -8,147 +8,15 @@ namespace TYLDDB.Utils /// A struct used to read a file
/// 用于读取文件的结构体 /// - public struct ReadFile + public struct Reader { /// - /// The earliest reading method based on FileStream + SreamReader.
- /// 最早的基于 FileStream + SreamReader 的读取方法。 + /// Read file.(64KB buffer)
+ /// 读取文件。(64KB缓冲区) ///
/// File path
文件路径 /// File content
文件内容
- /// - public static string ReadTylddbFile(string filePath) - { - try - { - using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) - using (StreamReader reader = new StreamReader(fs)) - { - string content = reader.ReadToEnd(); - return content; - } - } - catch (TylddbException ex) - { - throw new FileReadingFailException($"Error reading file: {ex.Message}"); - } - } - - /// - /// Select the desired method based on the file size
- /// 根据文件大小选择所需的方法 - /// <1MB - /// 1MB~10MB - /// 10MB~15MB - /// 15MB~20MB - /// 20MB~30MB - /// >30MB - ///
- /// File path
文件路径 - public static string ReadFileAuto(string filePath) - { - // 获取文件信息 - FileInfo fileInfo = new FileInfo(filePath); - - // 获取文件大小 (单位字节) - long fileSize = fileInfo.Length; - - // 根据文件大小区间进行不同的处理 - if (fileSize < 1 * 1024 * 1024) // 小于 1MB - { - return ReadSmallFile(filePath); - } - else if (fileSize < 10 * 1024 * 1024) // 小于 10MB - { - return ReadMediumFile(filePath); - } - else if(fileSize < 15 * 1024 * 1024) // 小于 15MB - { - return ReadLargeFile_8(filePath); - } - else if(fileSize < 20 * 1024 * 1024) // 小于 20MB - { - return ReadLargeFile_64(filePath); - } - else if (fileSize < 30 * 1024 * 1024) // 小于 30MB - { - return ReadLargeFile_128(filePath); - } - else // 大于 30MB - { - return ReadVeryLargeFile(filePath); - } - } - - /// - /// Read small file.
- /// 读取小文件。 - ///
- /// File path
文件路径 - /// File content
文件内容
- public static string ReadSmallFile(string filePath) => File.ReadAllText(filePath); - - /// - /// Read medium file.
- /// 读取中等大小文件。 - ///
- /// File path
文件路径 - /// File content
文件内容
- public static string ReadMediumFile(string filePath) - { - // 使用 FileStream 和 BufferedStream 进行高效读取 - StringBuilder fileContent = new StringBuilder(); // 用来存储文件内容 - - using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) - using (BufferedStream bs = new BufferedStream(fs)) - using (StreamReader reader = new StreamReader(bs, Encoding.UTF8)) - { - string line; - while ((line = reader.ReadLine()) != null) - { - // 将每一行的内容追加到 fileContent - fileContent.AppendLine(line); - } - } - - return fileContent.ToString(); // 返回文件的所有内容 - } - - /// - /// Read large file.(8KB buffer)
- /// 读取大文件。(8KB缓冲区) - ///
- /// File path
文件路径 - /// File content
文件内容
- public static string ReadLargeFile_8(string filePath) - { - // 这里采用分块读取文件的方式,避免一次性加载大文件 - const int bufferSize = 8192; // 8 KB缓冲区 - byte[] buffer = new byte[bufferSize]; - StringBuilder fileContent = new StringBuilder(); - - using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) - { - int bytesRead; - while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) - { - // 将每一块数据转换成字符串并累积到 fileContent 中 - string chunkContent = Encoding.UTF8.GetString(buffer, 0, bytesRead); - fileContent.Append(chunkContent); - } - } - - // 返回文件的全部内容 - return fileContent.ToString(); - } - - /// - /// Read large file.(64KB buffer)
- /// 读取大文件。(64KB缓冲区) - ///
- /// File path
文件路径 - /// File content
文件内容
- public static string ReadLargeFile_64(string filePath) + public static string ReadFile(string filePath) { // 这里采用分块读取文件的方式,避免一次性加载大文件 const int bufferSize = 65536; // 64 KB缓冲区 @@ -169,55 +37,5 @@ public static string ReadLargeFile_64(string filePath) // 返回文件的全部内容 return fileContent.ToString(); } - - /// - /// Read large file.(128KB buffer)
- /// 读取大文件。(128KB缓冲区) - ///
- /// File path
文件路径 - /// File content
文件内容
- public static string ReadLargeFile_128(string filePath) - { - // 这里采用分块读取文件的方式,避免一次性加载大文件 - const int bufferSize = 131072; // 128 KB缓冲区 - byte[] buffer = new byte[bufferSize]; - StringBuilder fileContent = new StringBuilder(); - - using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) - { - int bytesRead; - while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) - { - // 将每一块数据转换成字符串并累积到 fileContent 中 - string chunkContent = Encoding.UTF8.GetString(buffer, 0, bytesRead); - fileContent.Append(chunkContent); - } - } - - // 返回文件的全部内容 - return fileContent.ToString(); - } - - // 使用 MemoryMappedFile 读取非常大的文件 - /// - /// Read very large file.(Based on MemoryMappedFile)
- /// 读取很大的文件。(基于MemoryMappedFile) - ///
- /// File path
文件路径 - /// File content
文件内容
- public static string ReadVeryLargeFile(string filePath) - { - using (System.IO.MemoryMappedFiles.MemoryMappedFile mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(filePath, FileMode.Open)) - { - using (System.IO.MemoryMappedFiles.MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) - { - long length = accessor.Capacity; - byte[] buffer = new byte[length]; - accessor.ReadArray(0, buffer, 0, (int)length); - string content = Encoding.UTF8.GetString(buffer); - return content; - } - } - } } } From 364a659366074de7438d4584d6e530254aea4fdd Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Tue, 24 Dec 2024 17:07:07 +0800 Subject: [PATCH 14/52] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB.Test/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TYLDDB.Test/Program.cs b/TYLDDB.Test/Program.cs index 289cb0e..b4583a7 100644 --- a/TYLDDB.Test/Program.cs +++ b/TYLDDB.Test/Program.cs @@ -8,8 +8,8 @@ ///////////////////////////////////////////////////////////////////////////////////////////////////////// 读取文件 HighPrecisionTimer readDbTimer = new(); // 从发起读取文件到成功读取的总时间 -readDbTimer.Start(); lddb.FilePath = dbFilePath; +readDbTimer.Start(); lddb.ReadingFile(); readDbTimer.Stop(); WriteTime("从发起读取文件指令到成功读取的总时间为: ", readDbTimer.ElapsedMilliseconds()); From d815c530b3b8998253aac17246521dd370b0ddbb Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Tue, 24 Dec 2024 17:22:07 +0800 Subject: [PATCH 15/52] =?UTF-8?q?=E9=87=8D=E5=91=BD=E5=90=8D=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.cs | 37 +++++++++++++++++-------- TYLDDB/Utils/{ReadFile.cs => Reader.cs} | 0 TYLDDB/Utils/Writer.cs | 10 +++++++ 3 files changed, 36 insertions(+), 11 deletions(-) rename TYLDDB/Utils/{ReadFile.cs => Reader.cs} (100%) create mode 100644 TYLDDB/Utils/Writer.cs diff --git a/TYLDDB/TYLDDB.cs b/TYLDDB/TYLDDB.cs index 7741e03..6a3baa9 100644 --- a/TYLDDB/TYLDDB.cs +++ b/TYLDDB/TYLDDB.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using TYLDDB.Basic; using TYLDDB.Utils; @@ -9,19 +10,25 @@ namespace TYLDDB /// public class LDDB { - private string _filePath; // 私有字段存储文件路径 - private string _fileContent; // 私有字段存储文件内容 - private string _database; - private string _databaseContent; + /// + /// Instantiate the LDDB class
+ /// 实例化LDDB类 + ///
+ public LDDB() + { + // TODO + } + ///////////////////////////////////////////////////// 私有字段 + private string _filePath; // 存储文件路径 + private string _fileContent; // 存储文件内容 + private string _database; // 存储正在访问的数据库 + private string _databaseContent; // 存储数据库内容 private bool _isRead = false; // 是否已调用读取文件 - -#if NET6_0_OR_GREATER - private Database database = new(); -#else + private event Action OnFileReadComplete; private Database database = new Database(); -#endif + ///////////////////////////////////////////////////// 公开字段 /// /// Set the path where you want to read the file
/// 设置希望读取文件的路径 @@ -35,7 +42,6 @@ public string FilePath _filePath = value; // 只有通过验证后才设置值 } } - /// /// Names of all databases in the current file
/// 当前文件内所有数据库的名称 @@ -97,5 +103,14 @@ public string GetLoadingDatabaseContent() /// 读取全部数据库的名称 ///
public void ReadAllDatabaseName() => AllDatabaseName = database.GetDatabaseList(_fileContent); + + /// + /// Initialize the fast cache
+ /// 初始化快速缓存 + ///
+ public void QuickReadInitialize() + { + // TODO + } } } diff --git a/TYLDDB/Utils/ReadFile.cs b/TYLDDB/Utils/Reader.cs similarity index 100% rename from TYLDDB/Utils/ReadFile.cs rename to TYLDDB/Utils/Reader.cs diff --git a/TYLDDB/Utils/Writer.cs b/TYLDDB/Utils/Writer.cs new file mode 100644 index 0000000..75e8674 --- /dev/null +++ b/TYLDDB/Utils/Writer.cs @@ -0,0 +1,10 @@ +namespace TYLDDB.Utils +{ + /// + /// A class used to write contents into the file
+ /// 用于写入文件的类 + ///
+ public class Writer + { + } +} From a66e61ed081c93c24ac2351b4ec109af18676625 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Fri, 27 Dec 2024 21:48:29 +0800 Subject: [PATCH 16/52] =?UTF-8?q?=E5=BF=AB=E9=80=9F=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 基于线程锁 --- TYLDDB-CSharp.sln | 12 + .../HighPrecisionTimer.cs | 44 +++ TYLDDB.Utils.FastCache.Test/Program.cs | 76 +++++ .../TYLDDB.Utils.FastCache.Test.csproj | 14 + TYLDDB/TYLDDB.cs | 9 - TYLDDB/TYLDDB.csproj | 4 + TYLDDB/Utils/FastCache/Cache.cs | 286 ++++++++++++++++++ TYLDDB/Utils/Reader.cs | 1 - 8 files changed, 436 insertions(+), 10 deletions(-) create mode 100644 TYLDDB.Utils.FastCache.Test/HighPrecisionTimer.cs create mode 100644 TYLDDB.Utils.FastCache.Test/Program.cs create mode 100644 TYLDDB.Utils.FastCache.Test/TYLDDB.Utils.FastCache.Test.csproj create mode 100644 TYLDDB/Utils/FastCache/Cache.cs diff --git a/TYLDDB-CSharp.sln b/TYLDDB-CSharp.sln index 7d2180e..9ed67ba 100644 --- a/TYLDDB-CSharp.sln +++ b/TYLDDB-CSharp.sln @@ -12,6 +12,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TYLDDB.Test", "TYLDDB.Test\TYLDDB.Test.csproj", "{FDFD566C-CB13-43EB-970E-0EC0A21E36C0}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TYLDDB.Utils.FastCache.Test", "TYLDDB.Utils.FastCache.Test\TYLDDB.Utils.FastCache.Test.csproj", "{A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -26,10 +30,18 @@ Global {FDFD566C-CB13-43EB-970E-0EC0A21E36C0}.Debug|Any CPU.Build.0 = Debug|Any CPU {FDFD566C-CB13-43EB-970E-0EC0A21E36C0}.Release|Any CPU.ActiveCfg = Release|Any CPU {FDFD566C-CB13-43EB-970E-0EC0A21E36C0}.Release|Any CPU.Build.0 = Release|Any CPU + {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {FDFD566C-CB13-43EB-970E-0EC0A21E36C0} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} + {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} + EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {19390089-354C-41AD-AF7D-9FB3998A88EA} EndGlobalSection diff --git a/TYLDDB.Utils.FastCache.Test/HighPrecisionTimer.cs b/TYLDDB.Utils.FastCache.Test/HighPrecisionTimer.cs new file mode 100644 index 0000000..7856bfe --- /dev/null +++ b/TYLDDB.Utils.FastCache.Test/HighPrecisionTimer.cs @@ -0,0 +1,44 @@ +using System.Diagnostics; + +namespace TYLDDB.Utils.FastCache.Test +{ + internal class HighPrecisionTimer + { + private Stopwatch stopwatch; + + public HighPrecisionTimer() + { + stopwatch = new Stopwatch(); + } + + // 启动计时器 + public void Start() + { + stopwatch.Start(); + } + + // 停止计时器 + public void Stop() + { + stopwatch.Stop(); + } + + // 重置计时器 + public void Reset() + { + stopwatch.Reset(); + } + + // 获取已用时间(毫秒) + public double ElapsedMilliseconds() + { + return stopwatch.Elapsed.TotalMilliseconds; + } + + // 获取已用时间(秒) + public double ElapsedSeconds() + { + return stopwatch.Elapsed.TotalSeconds; + } + } +} diff --git a/TYLDDB.Utils.FastCache.Test/Program.cs b/TYLDDB.Utils.FastCache.Test/Program.cs new file mode 100644 index 0000000..da4dde3 --- /dev/null +++ b/TYLDDB.Utils.FastCache.Test/Program.cs @@ -0,0 +1,76 @@ +using TYLDDB.Utils.FastCache; +using TYLDDB.Utils.FastCache.Test; + +SemaphoreSlimDefault(); + +Console.ReadLine(); + +// 普通线程锁的数据库读写运行 +static async void SemaphoreSlimDefault() +{ + var setTime = new HighPrecisionTimer(); + var setAsyncTime = new HighPrecisionTimer(); + var getByKeyTime = new HighPrecisionTimer(); + var getByKeyAsyncTime = new HighPrecisionTimer(); + var getKeysByValueTime = new HighPrecisionTimer(); + var getKeysByValueAsyncTime = new HighPrecisionTimer(); + var getAllCacheTime = new HighPrecisionTimer(); + var getAllCacheAsyncTime = new HighPrecisionTimer(); + + var cache = new Cache(); + + setTime.Start(); + cache.Set("TESTKEY1", "TESTVALUE1"); + setTime.Stop(); + + setAsyncTime.Start(); + await cache.SetAsync("TESTKEY2", "TESTVALUE2"); + setAsyncTime.Stop(); + + getByKeyTime.Start(); + Console.WriteLine("TESTKEY1对应的值:" + cache.GetByKey("TESTKEY1")); + getByKeyTime.Stop(); + + getByKeyAsyncTime.Start(); + Console.WriteLine("TESTKEY2对应的值:" + await cache.GetByKeyAsync("TESTKEY2")); + getByKeyAsyncTime.Stop(); + + cache.Set("TESTKEY3", "TESTVALUE2"); + + Console.WriteLine("TESTVALUE2对应的所有键:"); + getKeysByValueTime.Start(); + Console.WriteLine(string.Join(", ", cache.GetKeysByValue("TESTVALUE2"))); + getKeysByValueTime.Stop(); + + Console.WriteLine("TESTVALUE2对应的所有键:"); + getKeysByValueAsyncTime.Start(); + Console.WriteLine(string.Join(", ", await cache.GetKeysByValueAsync("TESTVALUE2"))); + getKeysByValueAsyncTime.Stop(); + + // 获取并输出所有缓存项(同步方法) + getAllCacheTime.Start(); + var allCacheSync = cache.GetAllCache(); + Console.WriteLine("同步获取所有缓存项:"); + foreach (var kvp in allCacheSync) + { + Console.WriteLine($"{kvp.Key}: {kvp.Value}"); + } + getAllCacheTime.Stop(); + + // 获取并输出所有缓存项(异步方法) + getAllCacheAsyncTime.Start(); + var allCacheAsync = await cache.GetAllCacheAsync(); + Console.WriteLine("异步获取所有缓存项:"); + foreach (var kvp in allCacheAsync) + { + Console.WriteLine($"{kvp.Key}: {kvp.Value}"); + } + getAllCacheAsyncTime.Stop(); + + + Console.WriteLine("时间消耗:"); + Console.WriteLine($"设置键值(同步):{setTime.ElapsedMilliseconds()}ms 设置键值(异步):{setAsyncTime.ElapsedMilliseconds()}ms"); + Console.WriteLine($"根据键获取值(同步):{getByKeyTime.ElapsedMilliseconds()}ms 根据键获取值(异步):{getByKeyAsyncTime.ElapsedMilliseconds()}ms"); + Console.WriteLine($"根据值获取键(同步):{getKeysByValueTime.ElapsedMilliseconds()}ms 根据值获取键(异步):{getKeysByValueAsyncTime.ElapsedMilliseconds()}ms"); + Console.WriteLine($"获取所有缓存项(同步):{getAllCacheTime.ElapsedMilliseconds()}ms 获取所有缓存项(异步):{getAllCacheAsyncTime.ElapsedMilliseconds()}ms"); +} diff --git a/TYLDDB.Utils.FastCache.Test/TYLDDB.Utils.FastCache.Test.csproj b/TYLDDB.Utils.FastCache.Test/TYLDDB.Utils.FastCache.Test.csproj new file mode 100644 index 0000000..bb48fc4 --- /dev/null +++ b/TYLDDB.Utils.FastCache.Test/TYLDDB.Utils.FastCache.Test.csproj @@ -0,0 +1,14 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + diff --git a/TYLDDB/TYLDDB.cs b/TYLDDB/TYLDDB.cs index 6a3baa9..0fe14ba 100644 --- a/TYLDDB/TYLDDB.cs +++ b/TYLDDB/TYLDDB.cs @@ -103,14 +103,5 @@ public string GetLoadingDatabaseContent() /// 读取全部数据库的名称 ///
public void ReadAllDatabaseName() => AllDatabaseName = database.GetDatabaseList(_fileContent); - - /// - /// Initialize the fast cache
- /// 初始化快速缓存 - ///
- public void QuickReadInitialize() - { - // TODO - } } } diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index 55ebde2..2d745c6 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -37,4 +37,8 @@ + + + +
diff --git a/TYLDDB/Utils/FastCache/Cache.cs b/TYLDDB/Utils/FastCache/Cache.cs new file mode 100644 index 0000000..3551198 --- /dev/null +++ b/TYLDDB/Utils/FastCache/Cache.cs @@ -0,0 +1,286 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache +{ + /// + /// Use cached key-value pairs for fast reads and writes.
+ /// 使用缓存的键值对来快速读写。 + ///
+ public class Cache + { + private readonly Dictionary keyValueDict; // 存储键->值映射 + private readonly Dictionary> valueKeyDict; // 存储值->键的映射 + private readonly SemaphoreSlim semaphore; // 控制并发访问 + + /// + /// Use cached key-value pairs for fast reads and writes.
+ /// 使用缓存的键值对来快速读写。 + ///
+ public Cache() + { + keyValueDict = new Dictionary(); + valueKeyDict = new Dictionary>(); + semaphore = new SemaphoreSlim(1, 1); // 使用信号量来同步 + } + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public string GetByKey(string key) + { + lock (semaphore) + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + } + + /// + /// Asynchronous method: Obtains the corresponding value based on the key.
+ /// 异步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public async Task GetByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Synchronization method: Obtains one or more keys according to the value.
+ /// 同步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public List GetKeysByValue(string value) + { + lock (semaphore) + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + } + + /// + /// Asynchronous method: Get one or more keys based on the value.
+ /// 异步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public async Task> GetKeysByValueAsync(string value) + { + await semaphore.WaitAsync(); + try + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// 同步方法:设置一个键值对。 + /// + /// + /// + /// + public bool Set(string key, string value) + { + lock (semaphore) + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + } + + /// + /// 异步方法:设置一个键值对。 + /// + /// + /// + /// + public async Task SetAsync(string key, string value) + { + await semaphore.WaitAsync(); + try + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// 同步方法:移除一个键值对。 + /// + /// + /// + public bool RemoveByKey(string key) + { + lock (semaphore) + { + if (keyValueDict.ContainsKey(key)) + { + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + return false; + } + } + + /// + /// 异步方法:移除一个键值对。 + /// + /// + /// + public async Task RemoveByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + if (keyValueDict.ContainsKey(key)) + { + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + return false; + } + finally + { + semaphore.Release(); + } + } + + /// + /// 同步方法:清空缓存。 + /// + public void Clear() + { + lock (semaphore) + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + } + + /// + /// 异步方法:清空缓存。 + /// + /// + public async Task ClearAsync() + { + await semaphore.WaitAsync(); + try + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public Dictionary GetAllCache() + { + lock (semaphore) + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public async Task> GetAllCacheAsync() + { + await semaphore.WaitAsync(); + try + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + finally + { + semaphore.Release(); + } + } + } +} diff --git a/TYLDDB/Utils/Reader.cs b/TYLDDB/Utils/Reader.cs index 31ecbe3..68e9949 100644 --- a/TYLDDB/Utils/Reader.cs +++ b/TYLDDB/Utils/Reader.cs @@ -1,6 +1,5 @@ using System.IO; using System.Text; -using TYLDDB.Basic; namespace TYLDDB.Utils { From 80eeca393b9182011b7091c64acb07156a5d6218 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Fri, 27 Dec 2024 23:08:07 +0800 Subject: [PATCH 17/52] =?UTF-8?q?=E6=9B=B4=E6=96=B0readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a5d8330..5d82374 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ # TYLDDB-C# C# version. + +A strongly typed constrained distributed file system that can act as a database. From 4920f4e40ecd530a16022595fa6bd4fc89c2c8ae Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Fri, 27 Dec 2024 23:08:16 +0800 Subject: [PATCH 18/52] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.csproj | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index 2d745c6..4a1776d 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -4,7 +4,7 @@ netstandard2.0;netstandard2.1;net6.0;net8.0;net9.0 True TTYPDB.NET - 1.0.0-beta.1 + 1.0.0-alpha.1 QingYi-Studio LICENSE True @@ -20,10 +20,12 @@ + + True \ From 9c48a8b87b7e92bcb370a465e720147889bc4bb7 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Fri, 27 Dec 2024 23:30:54 +0800 Subject: [PATCH 19/52] =?UTF-8?q?feat:=20=E4=BD=BF=E7=94=A8=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB.Utils.FastCache.Test/Program.cs | 2 +- TYLDDB/Utils/FastCache/ICache.cs | 99 +++++++++++++++++++ .../{Cache.cs => SemaphoreThreadLock.cs} | 8 +- 3 files changed, 104 insertions(+), 5 deletions(-) create mode 100644 TYLDDB/Utils/FastCache/ICache.cs rename TYLDDB/Utils/FastCache/{Cache.cs => SemaphoreThreadLock.cs} (97%) diff --git a/TYLDDB.Utils.FastCache.Test/Program.cs b/TYLDDB.Utils.FastCache.Test/Program.cs index da4dde3..6b965ac 100644 --- a/TYLDDB.Utils.FastCache.Test/Program.cs +++ b/TYLDDB.Utils.FastCache.Test/Program.cs @@ -17,7 +17,7 @@ static async void SemaphoreSlimDefault() var getAllCacheTime = new HighPrecisionTimer(); var getAllCacheAsyncTime = new HighPrecisionTimer(); - var cache = new Cache(); + ICache cache = new SemaphoreThreadLock(); setTime.Start(); cache.Set("TESTKEY1", "TESTVALUE1"); diff --git a/TYLDDB/Utils/FastCache/ICache.cs b/TYLDDB/Utils/FastCache/ICache.cs new file mode 100644 index 0000000..76561be --- /dev/null +++ b/TYLDDB/Utils/FastCache/ICache.cs @@ -0,0 +1,99 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache +{ + /// + /// Use cached key-value pairs for fast reads and writes.
+ /// 使用缓存的键值对来快速读写。 + ///
+ public interface ICache + { + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ string GetByKey(string key); + + /// + /// Asynchronous method: Obtains the corresponding value based on the key.
+ /// 异步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ Task GetByKeyAsync(string key); + + /// + /// Synchronization method: Obtains one or more keys according to the value.
+ /// 同步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ List GetKeysByValue(string value); + + /// + /// Asynchronous method: Get one or more keys based on the value.
+ /// 异步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ Task> GetKeysByValueAsync(string value); + + /// + /// 同步方法:设置一个键值对。 + /// + /// + /// + /// + bool Set(string key, string value); + + /// + /// 异步方法:设置一个键值对。 + /// + /// + /// + /// + Task SetAsync(string key, string value); + + /// + /// 同步方法:移除一个键值对。 + /// + /// + /// + bool RemoveByKey(string key); + + /// + /// 异步方法:移除一个键值对。 + /// + /// + /// + Task RemoveByKeyAsync(string key); + + /// + /// 同步方法:清空缓存。 + /// + void Clear(); + + /// + /// 异步方法:清空缓存。 + /// + /// + Task ClearAsync(); + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ Dictionary GetAllCache(); + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ Task> GetAllCacheAsync(); + } +} diff --git a/TYLDDB/Utils/FastCache/Cache.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs similarity index 97% rename from TYLDDB/Utils/FastCache/Cache.cs rename to TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs index 3551198..2745702 100644 --- a/TYLDDB/Utils/FastCache/Cache.cs +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs @@ -6,10 +6,10 @@ namespace TYLDDB.Utils.FastCache { /// - /// Use cached key-value pairs for fast reads and writes.
- /// 使用缓存的键值对来快速读写。 + /// Use semaphore based thread locks to achieve high concurrency stability.
+ /// 使用基于信号量的线程锁来实现高并发的稳定性。 ///
- public class Cache + public class SemaphoreThreadLock : ICache { private readonly Dictionary keyValueDict; // 存储键->值映射 private readonly Dictionary> valueKeyDict; // 存储值->键的映射 @@ -19,7 +19,7 @@ public class Cache /// Use cached key-value pairs for fast reads and writes.
/// 使用缓存的键值对来快速读写。 /// - public Cache() + public SemaphoreThreadLock() { keyValueDict = new Dictionary(); valueKeyDict = new Dictionary>(); From a218cc11d902d8303dd3d5669251e664586dcbf7 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Fri, 27 Dec 2024 23:39:24 +0800 Subject: [PATCH 20/52] =?UTF-8?q?refactor:=20=E4=BB=A3=E7=A0=81=E7=95=A5?= =?UTF-8?q?=E5=BE=AE=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 部分if转换为switch语句 减少嵌套(提前返回) --- TYLDDB/TYLDDB.cs | 22 +++++----- TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs | 44 +++++++++---------- 2 files changed, 32 insertions(+), 34 deletions(-) diff --git a/TYLDDB/TYLDDB.cs b/TYLDDB/TYLDDB.cs index 0fe14ba..359ce37 100644 --- a/TYLDDB/TYLDDB.cs +++ b/TYLDDB/TYLDDB.cs @@ -78,25 +78,23 @@ public void ReadingFile() /// name of the database
数据库名称 public void LoadDatabase(string db) { - if (_isRead == true) + switch (_isRead) { - _databaseContent = database.GetDatabaseContent(_fileContent, db); - } - else - { - ReadingFile(); - _databaseContent = database.GetDatabaseContent(_fileContent, db); - } + case true: + _databaseContent = database.GetDatabaseContent(_fileContent, db); + break; + default: + ReadingFile(); + _databaseContent = database.GetDatabaseContent(_fileContent, db); + break; } + } /// /// Gets the contents of the database being loaded
/// 获取正在加载的数据库内容 ///
- public string GetLoadingDatabaseContent() - { - return _databaseContent; - } + public string GetLoadingDatabaseContent() => _databaseContent; /// /// Read the names of all databases
diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs index 2745702..ff661cd 100644 --- a/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs @@ -168,22 +168,22 @@ public bool RemoveByKey(string key) { lock (semaphore) { - if (keyValueDict.ContainsKey(key)) + if (!keyValueDict.ContainsKey(key)) { - var value = keyValueDict[key]; - keyValueDict.Remove(key); + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); - if (valueKeyDict.ContainsKey(value)) + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) { - valueKeyDict[value].Remove(key); - if (valueKeyDict[value].Count == 0) - { - valueKeyDict.Remove(value); - } + valueKeyDict.Remove(value); } - return true; } - return false; + return true; } } @@ -197,22 +197,22 @@ public async Task RemoveByKeyAsync(string key) await semaphore.WaitAsync(); try { - if (keyValueDict.ContainsKey(key)) + if (!keyValueDict.ContainsKey(key)) { - var value = keyValueDict[key]; - keyValueDict.Remove(key); + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); - if (valueKeyDict.ContainsKey(value)) + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) { - valueKeyDict[value].Remove(key); - if (valueKeyDict[value].Count == 0) - { - valueKeyDict.Remove(value); - } + valueKeyDict.Remove(value); } - return true; } - return false; + return true; } finally { From 870ca7f39ae8b98d6cf15f448936508dc0c4de91 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Fri, 27 Dec 2024 23:39:34 +0800 Subject: [PATCH 21/52] =?UTF-8?q?docs:=20=E6=9B=B4=E6=96=B0=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index 4a1776d..f292232 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -4,7 +4,7 @@ netstandard2.0;netstandard2.1;net6.0;net8.0;net9.0 True TTYPDB.NET - 1.0.0-alpha.1 + 1.0.0-alpha.2 QingYi-Studio LICENSE True From 3449d16cfd94ad1d14252f29f9cec956a614493a Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Fri, 27 Dec 2024 23:41:44 +0800 Subject: [PATCH 22/52] =?UTF-8?q?docs:=20=E8=B0=83=E6=95=B4=E6=89=93?= =?UTF-8?q?=E5=8C=85=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.csproj | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index f292232..bcfe601 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -5,7 +5,7 @@ True TTYPDB.NET 1.0.0-alpha.2 - QingYi-Studio + TYLDDB-Project LICENSE True icon.png @@ -17,6 +17,8 @@ True True DataBase + QingYi-Studio + README.md @@ -37,6 +39,10 @@ True \ + + True + \ + From 54268c9b5e856b02ac2e78d354efaec87bafc1f8 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Fri, 27 Dec 2024 23:55:28 +0800 Subject: [PATCH 23/52] =?UTF-8?q?feat:=20=E5=B0=9D=E8=AF=95=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E6=9B=B4=E5=BF=AB=E7=9A=84=E5=B9=B6=E5=8F=91=E8=AF=8D?= =?UTF-8?q?=E5=85=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB.Utils.FastCache.Test/Program.cs | 75 ++++++++- .../Utils/FastCache/ConcurrentDictionary.cs | 159 ++++++++++++++++++ 2 files changed, 233 insertions(+), 1 deletion(-) create mode 100644 TYLDDB/Utils/FastCache/ConcurrentDictionary.cs diff --git a/TYLDDB.Utils.FastCache.Test/Program.cs b/TYLDDB.Utils.FastCache.Test/Program.cs index 6b965ac..4d623c8 100644 --- a/TYLDDB.Utils.FastCache.Test/Program.cs +++ b/TYLDDB.Utils.FastCache.Test/Program.cs @@ -1,11 +1,15 @@ using TYLDDB.Utils.FastCache; using TYLDDB.Utils.FastCache.Test; +Console.WriteLine("基于信号量的缓存读写运行"); SemaphoreSlimDefault(); +Console.WriteLine(); +Console.WriteLine("基于信号量的缓存读写运行"); +ConcurrentDictionary(); Console.ReadLine(); -// 普通线程锁的数据库读写运行 +// 基于信号量的缓存读写运行 static async void SemaphoreSlimDefault() { var setTime = new HighPrecisionTimer(); @@ -68,6 +72,75 @@ static async void SemaphoreSlimDefault() getAllCacheAsyncTime.Stop(); + Console.WriteLine("时间消耗:"); + Console.WriteLine($"设置键值(同步):{setTime.ElapsedMilliseconds()}ms 设置键值(异步):{setAsyncTime.ElapsedMilliseconds()}ms"); + Console.WriteLine($"根据键获取值(同步):{getByKeyTime.ElapsedMilliseconds()}ms 根据键获取值(异步):{getByKeyAsyncTime.ElapsedMilliseconds()}ms"); + Console.WriteLine($"根据值获取键(同步):{getKeysByValueTime.ElapsedMilliseconds()}ms 根据值获取键(异步):{getKeysByValueAsyncTime.ElapsedMilliseconds()}ms"); + Console.WriteLine($"获取所有缓存项(同步):{getAllCacheTime.ElapsedMilliseconds()}ms 获取所有缓存项(异步):{getAllCacheAsyncTime.ElapsedMilliseconds()}ms"); +} + +// 基于并发词典的缓存读写运行 +static async void ConcurrentDictionary() +{ + var setTime = new HighPrecisionTimer(); + var setAsyncTime = new HighPrecisionTimer(); + var getByKeyTime = new HighPrecisionTimer(); + var getByKeyAsyncTime = new HighPrecisionTimer(); + var getKeysByValueTime = new HighPrecisionTimer(); + var getKeysByValueAsyncTime = new HighPrecisionTimer(); + var getAllCacheTime = new HighPrecisionTimer(); + var getAllCacheAsyncTime = new HighPrecisionTimer(); + + ICache cache = new ConcurrentDictionary(); + + setTime.Start(); + cache.Set("TESTKEY1", "TESTVALUE1"); + setTime.Stop(); + + setAsyncTime.Start(); + await cache.SetAsync("TESTKEY2", "TESTVALUE2"); + setAsyncTime.Stop(); + + getByKeyTime.Start(); + Console.WriteLine("TESTKEY1对应的值:" + cache.GetByKey("TESTKEY1")); + getByKeyTime.Stop(); + + getByKeyAsyncTime.Start(); + Console.WriteLine("TESTKEY2对应的值:" + await cache.GetByKeyAsync("TESTKEY2")); + getByKeyAsyncTime.Stop(); + + cache.Set("TESTKEY3", "TESTVALUE2"); + + Console.WriteLine("TESTVALUE2对应的所有键:"); + getKeysByValueTime.Start(); + Console.WriteLine(string.Join(", ", cache.GetKeysByValue("TESTVALUE2"))); + getKeysByValueTime.Stop(); + + Console.WriteLine("TESTVALUE2对应的所有键:"); + getKeysByValueAsyncTime.Start(); + Console.WriteLine(string.Join(", ", await cache.GetKeysByValueAsync("TESTVALUE2"))); + getKeysByValueAsyncTime.Stop(); + + // 获取并输出所有缓存项(同步方法) + getAllCacheTime.Start(); + var allCacheSync = cache.GetAllCache(); + Console.WriteLine("同步获取所有缓存项:"); + foreach (var kvp in allCacheSync) + { + Console.WriteLine($"{kvp.Key}: {kvp.Value}"); + } + getAllCacheTime.Stop(); + + // 获取并输出所有缓存项(异步方法) + getAllCacheAsyncTime.Start(); + var allCacheAsync = await cache.GetAllCacheAsync(); + Console.WriteLine("异步获取所有缓存项:"); + foreach (var kvp in allCacheAsync) + { + Console.WriteLine($"{kvp.Key}: {kvp.Value}"); + } + getAllCacheAsyncTime.Stop(); + Console.WriteLine("时间消耗:"); Console.WriteLine($"设置键值(同步):{setTime.ElapsedMilliseconds()}ms 设置键值(异步):{setAsyncTime.ElapsedMilliseconds()}ms"); Console.WriteLine($"根据键获取值(同步):{getByKeyTime.ElapsedMilliseconds()}ms 根据键获取值(异步):{getByKeyAsyncTime.ElapsedMilliseconds()}ms"); diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary.cs new file mode 100644 index 0000000..55a4d5f --- /dev/null +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary.cs @@ -0,0 +1,159 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache +{ + /// + /// Use thread locks based on concurrent dictionaries to achieve high concurrency stability.
+ /// 使用基于信号量的线程锁来实现高并发的稳定性。 + ///
+ public class ConcurrentDictionary : ICache + { + /// + /// Thread-safe dictionary to store cache data.
+ /// 线程安全的字典,用于存储缓存数据。 + ///
+ private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public string GetByKey(string key) + { + _cache.TryGetValue(key, out var value); + return value; + } + + /// + /// Asynchronous method to get the corresponding value by key.
+ /// 异步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public async Task GetByKeyAsync(string key) + { + return await Task.FromResult(GetByKey(key)); + } + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public List GetKeysByValue(string value) + { + var keys = new List(); + foreach (var kvp in _cache) + { + if (kvp.Value == value) + { + keys.Add(kvp.Key); + } + } + return keys; + } + + /// + /// Asynchronous method to get a list of keys that correspond to a specific value.
+ /// 异步方法:获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public async Task> GetKeysByValueAsync(string value) + { + return await Task.FromResult(GetKeysByValue(value)); + } + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public bool Set(string key, string value) + { + // Using AddOrUpdate to ensure atomic insert or update operation + _cache.AddOrUpdate(key, value, (existingKey, existingValue) => value); + return true; + } + + /// + /// Asynchronous method to set a cache entry for a specified key.
+ /// 异步方法:为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public async Task SetAsync(string key, string value) + { + return await Task.FromResult(Set(key, value)); + } + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public bool RemoveByKey(string key) + { + return _cache.TryRemove(key, out _); + } + + /// + /// Asynchronous method to remove a cache entry by its key.
+ /// 异步方法:根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public async Task RemoveByKeyAsync(string key) + { + return await Task.FromResult(RemoveByKey(key)); + } + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public void Clear() + { + _cache.Clear(); + } + + /// + /// Asynchronous method to clear all cache entries.
+ /// 异步方法:清空所有缓存项。 + ///
+ /// Asynchronous task for clearing.
清空操作的异步任务。
+ public async Task ClearAsync() + { + await Task.Run(() => Clear()); + } + + /// + /// Get all cache entries as a dictionary.
+ /// 获取所有缓存项,返回字典。 + ///
+ /// All cache entries as a dictionary.
所有缓存项的字典。
+ public Dictionary GetAllCache() + { + return new Dictionary(_cache); + } + + /// + /// Asynchronous method to get all cache entries as a dictionary.
+ /// 异步方法:获取所有缓存项,返回字典。 + ///
+ /// All cache entries as a dictionary.
所有缓存项的字典。
+ public async Task> GetAllCacheAsync() + { + return await Task.FromResult(GetAllCache()); + } + } +} From 510cbf41408667641d121ff5db52d0664b60dc05 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sat, 28 Dec 2024 15:06:56 +0800 Subject: [PATCH 24/52] =?UTF-8?q?refactor:=20=E4=BD=BF=E7=94=A8=E6=8A=BD?= =?UTF-8?q?=E8=B1=A1=E7=B1=BB=E6=9D=A5=E8=BF=87=E6=B8=A1=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E4=B8=8E=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.csproj | 2 +- TYLDDB/Utils/FastCache/Cache.cs | 39 +++++++++ .../Utils/FastCache/ConcurrentDictionary.cs | 85 ++----------------- TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs | 26 +++--- 4 files changed, 60 insertions(+), 92 deletions(-) create mode 100644 TYLDDB/Utils/FastCache/Cache.cs diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index bcfe601..4d2cfb8 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -1,7 +1,7 @@  - netstandard2.0;netstandard2.1;net6.0;net8.0;net9.0 + netstandard2.1;net6.0;net8.0;net9.0 True TTYPDB.NET 1.0.0-alpha.2 diff --git a/TYLDDB/Utils/FastCache/Cache.cs b/TYLDDB/Utils/FastCache/Cache.cs new file mode 100644 index 0000000..dc06ba2 --- /dev/null +++ b/TYLDDB/Utils/FastCache/Cache.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache +{ + /// + /// For cached abstract classes, you need to inherit the class to do concrete implementation.
+ /// 对于缓存的抽象类,需要继承该类来做具体实现。 + ///
+ public abstract class Cache : ICache + { + /// + public abstract void Clear(); + /// + public virtual async Task ClearAsync() => await Task.Run(() => Clear()); + /// + public abstract Dictionary GetAllCache(); + /// + public virtual async Task> GetAllCacheAsync() => await Task.FromResult(GetAllCache()); + /// + public abstract string GetByKey(string key); + /// + public virtual async Task GetByKeyAsync(string key) => await Task.FromResult(GetByKey(key)); + /// + public abstract List GetKeysByValue(string value); + /// + public virtual async Task> GetKeysByValueAsync(string value) => await Task.FromResult(GetKeysByValue(value)); + /// + public abstract bool RemoveByKey(string key); + /// + public virtual async Task RemoveByKeyAsync(string key) => await Task.FromResult(RemoveByKey(key)); + /// + public abstract bool Set(string key, string value); + /// + public virtual async Task SetAsync(string key, string value) => await Task.FromResult(Set(key, value)); + } +} diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary.cs index 55a4d5f..e8c4ee1 100644 --- a/TYLDDB/Utils/FastCache/ConcurrentDictionary.cs +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary.cs @@ -8,7 +8,7 @@ namespace TYLDDB.Utils.FastCache /// Use thread locks based on concurrent dictionaries to achieve high concurrency stability.
/// 使用基于信号量的线程锁来实现高并发的稳定性。 ///
- public class ConcurrentDictionary : ICache + public class ConcurrentDictionary : Cache { /// /// Thread-safe dictionary to store cache data.
@@ -22,30 +22,19 @@ public class ConcurrentDictionary : ICache ///
/// Key
键 /// Value
- public string GetByKey(string key) + public override string GetByKey(string key) { _cache.TryGetValue(key, out var value); return value; } - /// - /// Asynchronous method to get the corresponding value by key.
- /// 异步方法:根据键获取对应的值。 - ///
- /// Key
键 - /// Value
- public async Task GetByKeyAsync(string key) - { - return await Task.FromResult(GetByKey(key)); - } - /// /// Get a list of keys that correspond to a specific value.
/// 获取与指定值对应的所有键的列表。 ///
/// Value to match
要匹配的值 /// List of keys
键的列表
- public List GetKeysByValue(string value) + public override List GetKeysByValue(string value) { var keys = new List(); foreach (var kvp in _cache) @@ -58,17 +47,6 @@ public List GetKeysByValue(string value) return keys; } - /// - /// Asynchronous method to get a list of keys that correspond to a specific value.
- /// 异步方法:获取与指定值对应的所有键的列表。 - ///
- /// Value to match
要匹配的值 - /// List of keys
键的列表
- public async Task> GetKeysByValueAsync(string value) - { - return await Task.FromResult(GetKeysByValue(value)); - } - /// /// Set a cache entry for a specified key.
/// 为指定键设置缓存项。 @@ -76,84 +54,35 @@ public async Task> GetKeysByValueAsync(string value) /// Key
键 /// Value
值 /// Whether the operation is successful.
操作是否成功。
- public bool Set(string key, string value) + public override bool Set(string key, string value) { // Using AddOrUpdate to ensure atomic insert or update operation _cache.AddOrUpdate(key, value, (existingKey, existingValue) => value); return true; } - /// - /// Asynchronous method to set a cache entry for a specified key.
- /// 异步方法:为指定键设置缓存项。 - ///
- /// Key
键 - /// Value
值 - /// Whether the operation is successful.
操作是否成功。
- public async Task SetAsync(string key, string value) - { - return await Task.FromResult(Set(key, value)); - } - /// /// Remove a cache entry by its key.
/// 根据键移除缓存项。 ///
/// Key
键 /// Whether the removal is successful.
移除操作是否成功。
- public bool RemoveByKey(string key) + public override bool RemoveByKey(string key) { return _cache.TryRemove(key, out _); } - /// - /// Asynchronous method to remove a cache entry by its key.
- /// 异步方法:根据键移除缓存项。 - ///
- /// Key
键 - /// Whether the removal is successful.
移除操作是否成功。
- public async Task RemoveByKeyAsync(string key) - { - return await Task.FromResult(RemoveByKey(key)); - } - /// /// Clear all cache entries.
/// 清空所有缓存项。 ///
- public void Clear() - { - _cache.Clear(); - } - - /// - /// Asynchronous method to clear all cache entries.
- /// 异步方法:清空所有缓存项。 - ///
- /// Asynchronous task for clearing.
清空操作的异步任务。
- public async Task ClearAsync() - { - await Task.Run(() => Clear()); - } + public override void Clear() => _cache.Clear(); /// /// Get all cache entries as a dictionary.
/// 获取所有缓存项,返回字典。 ///
/// All cache entries as a dictionary.
所有缓存项的字典。
- public Dictionary GetAllCache() - { - return new Dictionary(_cache); - } - - /// - /// Asynchronous method to get all cache entries as a dictionary.
- /// 异步方法:获取所有缓存项,返回字典。 - ///
- /// All cache entries as a dictionary.
所有缓存项的字典。
- public async Task> GetAllCacheAsync() - { - return await Task.FromResult(GetAllCache()); - } + public override Dictionary GetAllCache() => new Dictionary(_cache); } } diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs index ff661cd..2002ced 100644 --- a/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs @@ -9,7 +9,7 @@ namespace TYLDDB.Utils.FastCache /// Use semaphore based thread locks to achieve high concurrency stability.
/// 使用基于信号量的线程锁来实现高并发的稳定性。 ///
- public class SemaphoreThreadLock : ICache + public class SemaphoreThreadLock : Cache { private readonly Dictionary keyValueDict; // 存储键->值映射 private readonly Dictionary> valueKeyDict; // 存储值->键的映射 @@ -32,7 +32,7 @@ public SemaphoreThreadLock() /// /// Key
键 /// Value
- public string GetByKey(string key) + public override string GetByKey(string key) { lock (semaphore) { @@ -47,7 +47,7 @@ public string GetByKey(string key) /// /// Key
键 /// Value
- public async Task GetByKeyAsync(string key) + public override async Task GetByKeyAsync(string key) { await semaphore.WaitAsync(); try @@ -67,7 +67,7 @@ public async Task GetByKeyAsync(string key) /// /// Value
值 /// Key (List)
键 (List)
- public List GetKeysByValue(string value) + public override List GetKeysByValue(string value) { lock (semaphore) { @@ -85,7 +85,7 @@ public List GetKeysByValue(string value) /// /// Value
值 /// Key (List)
键 (List)
- public async Task> GetKeysByValueAsync(string value) + public override async Task> GetKeysByValueAsync(string value) { await semaphore.WaitAsync(); try @@ -108,7 +108,7 @@ public async Task> GetKeysByValueAsync(string value) /// /// /// - public bool Set(string key, string value) + public override bool Set(string key, string value) { lock (semaphore) { @@ -134,7 +134,7 @@ public bool Set(string key, string value) /// /// /// - public async Task SetAsync(string key, string value) + public override async Task SetAsync(string key, string value) { await semaphore.WaitAsync(); try @@ -164,7 +164,7 @@ public async Task SetAsync(string key, string value) /// /// /// - public bool RemoveByKey(string key) + public override bool RemoveByKey(string key) { lock (semaphore) { @@ -192,7 +192,7 @@ public bool RemoveByKey(string key) /// /// /// - public async Task RemoveByKeyAsync(string key) + public override async Task RemoveByKeyAsync(string key) { await semaphore.WaitAsync(); try @@ -223,7 +223,7 @@ public async Task RemoveByKeyAsync(string key) /// /// 同步方法:清空缓存。 /// - public void Clear() + public override void Clear() { lock (semaphore) { @@ -236,7 +236,7 @@ public void Clear() /// 异步方法:清空缓存。 /// /// - public async Task ClearAsync() + public override async Task ClearAsync() { await semaphore.WaitAsync(); try @@ -255,7 +255,7 @@ public async Task ClearAsync() /// 获取所有的键值对。 /// /// Key-value pair
键值对
- public Dictionary GetAllCache() + public override Dictionary GetAllCache() { lock (semaphore) { @@ -269,7 +269,7 @@ public Dictionary GetAllCache() /// 获取所有的键值对。 /// /// Key-value pair
键值对
- public async Task> GetAllCacheAsync() + public override async Task> GetAllCacheAsync() { await semaphore.WaitAsync(); try From d12e130c1620c4a1db606079caefede92c7e4830 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sat, 28 Dec 2024 15:16:04 +0800 Subject: [PATCH 25/52] =?UTF-8?q?docs:=20=E6=B7=BB=E5=8A=A0=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.csproj | 6 ++++-- TYLDDB/Utils/FastCache/ConcurrentDictionary.cs | 1 - 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index 4d2cfb8..ccc2630 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -3,8 +3,8 @@ netstandard2.1;net6.0;net8.0;net9.0 True - TTYPDB.NET - 1.0.0-alpha.2 + TYLDDB.NET + 1.0.0-alpha.2r TYLDDB-Project LICENSE True @@ -19,6 +19,8 @@ DataBase QingYi-Studio README.md + Remove support for .netstandard 2.0. +Remove direct inheritance/derivation of the ICache interface and instead use abstract class relays, using virtual methods to trim asynchronous code in part of the concurrent dictionary. diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary.cs index e8c4ee1..6382d31 100644 --- a/TYLDDB/Utils/FastCache/ConcurrentDictionary.cs +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary.cs @@ -1,6 +1,5 @@ using System.Collections.Concurrent; using System.Collections.Generic; -using System.Threading.Tasks; namespace TYLDDB.Utils.FastCache { From 8a1047dd07d5e4d6f4d8648bfaa6f9d1c6623edf Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sat, 28 Dec 2024 15:38:25 +0800 Subject: [PATCH 26/52] =?UTF-8?q?docs:=20=E4=BF=AE=E6=94=B9=E7=89=88?= =?UTF-8?q?=E6=9D=83=E5=A3=B0=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LICENSE | 11 ++++------ LICENSE_CN | 48 ++++++++++++++++++++++++++++++++++++++++++++ TYLDDB/LICENSE | 25 +++++++++++++++++++++++ TYLDDB/LICENSE_CN | 48 ++++++++++++++++++++++++++++++++++++++++++++ TYLDDB/TYLDDB.csproj | 13 +++++++----- 5 files changed, 133 insertions(+), 12 deletions(-) create mode 100644 LICENSE_CN create mode 100644 TYLDDB/LICENSE create mode 100644 TYLDDB/LICENSE_CN diff --git a/LICENSE b/LICENSE index 9fa3e69..afa0540 100644 --- a/LICENSE +++ b/LICENSE @@ -1,18 +1,15 @@ -BSD 3-Clause License +Change the License based on BSD 3-Clause Copyright (c) 2024, Tsing Yi Local Distributed Database -Redistribution and use in source and binary forms, with or without +Redistribution and use in binary forms, with or without modification, are permitted provided that the following conditions are met: -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, +1. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -3. Neither the name of the copyright holder nor the names of its +2. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. diff --git a/LICENSE_CN b/LICENSE_CN new file mode 100644 index 0000000..b3a735f --- /dev/null +++ b/LICENSE_CN @@ -0,0 +1,48 @@ +基于 BSD 3-Clause License 修改 + +Copyright (c) 2024, Tsing Yi Local Distributed Database + +在满足以下条件的情况下,允许以二进制形式重新分发和使用,无论是否进行修改: + +1. 以二进制形式重新分发必须在文件和/或随分发提供的其他材料中复制上述版权声明、本 + 条件列表和以下免责声明。 + +2. 未经事先书面许可,不得使用版权所有者的名字或贡献者的名字来支持或推广源自本软件 + 的产品。 + +3. 以下子条件针对所有中国大陆公司,内部所有国家均指中国大陆: + + 3.1 不得将本软件用于任何与国家法律、法规和政策相抵触的活动。 + + 3.2 不得将本软件用于任何可能损害国家安全、社会公共利益或他人合法权益的活动。 + + 3.3 不得将本软件用于任何可能侵犯他人知识产权的活动。 + + 3.4 不得将本软件用于任何可能违反国家法律法规的活动。 + + 3.5 不得将本软件用于任何可能损害国家信息安全的活动。 + + 3.6 不得将本软件用于任何可能损害国家政治稳定的活动。 + + 3.7 不得将本软件用于任何可能损害国家经济利益的活动。 + + 3.8 不得将本软件用于任何可能损害国家文化利益的活动。 + + 3.9 不得将本软件用于任何可能损害国家形象的活动。 + + 3.10 不得将本软件用于任何可能损害国家荣誉的活动。 + + 3.11 不得将本软件用于任何可能损害国家尊严的活动。 + + 3.12 不得在未经书面许可的情况下将该程序商用。 + + 3.13 由于该程序造成的损失本程序作者与团队概不负责。 + + 3.14 未经书面许可禁止将本项目代码商用。 + +本软件由版权持有人和贡献者“按原样”提供,不承担任何明示或暗示的保证,包括但不限于对 +适销性和适合特定目的的暗示保证。在任何情况下,版权持有人或贡献者均不对任何直接、间 +接、附带、特殊、惩戒性或后果性损害(包括但不限于,购买替代商品或服务;损失:失去使用 +、数据或利润;(或业务中断),无论如何造成的,以及根据任何责任理论,无论是合同责任, +严格责任,还是侵权行为(包括疏忽或其他),即使被告知该等损害的可能性,也会因使用本 +软件而以任何方式产生。 diff --git a/TYLDDB/LICENSE b/TYLDDB/LICENSE new file mode 100644 index 0000000..afa0540 --- /dev/null +++ b/TYLDDB/LICENSE @@ -0,0 +1,25 @@ +Change the License based on BSD 3-Clause + +Copyright (c) 2024, Tsing Yi Local Distributed Database + +Redistribution and use in binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +2. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/TYLDDB/LICENSE_CN b/TYLDDB/LICENSE_CN new file mode 100644 index 0000000..b3a735f --- /dev/null +++ b/TYLDDB/LICENSE_CN @@ -0,0 +1,48 @@ +基于 BSD 3-Clause License 修改 + +Copyright (c) 2024, Tsing Yi Local Distributed Database + +在满足以下条件的情况下,允许以二进制形式重新分发和使用,无论是否进行修改: + +1. 以二进制形式重新分发必须在文件和/或随分发提供的其他材料中复制上述版权声明、本 + 条件列表和以下免责声明。 + +2. 未经事先书面许可,不得使用版权所有者的名字或贡献者的名字来支持或推广源自本软件 + 的产品。 + +3. 以下子条件针对所有中国大陆公司,内部所有国家均指中国大陆: + + 3.1 不得将本软件用于任何与国家法律、法规和政策相抵触的活动。 + + 3.2 不得将本软件用于任何可能损害国家安全、社会公共利益或他人合法权益的活动。 + + 3.3 不得将本软件用于任何可能侵犯他人知识产权的活动。 + + 3.4 不得将本软件用于任何可能违反国家法律法规的活动。 + + 3.5 不得将本软件用于任何可能损害国家信息安全的活动。 + + 3.6 不得将本软件用于任何可能损害国家政治稳定的活动。 + + 3.7 不得将本软件用于任何可能损害国家经济利益的活动。 + + 3.8 不得将本软件用于任何可能损害国家文化利益的活动。 + + 3.9 不得将本软件用于任何可能损害国家形象的活动。 + + 3.10 不得将本软件用于任何可能损害国家荣誉的活动。 + + 3.11 不得将本软件用于任何可能损害国家尊严的活动。 + + 3.12 不得在未经书面许可的情况下将该程序商用。 + + 3.13 由于该程序造成的损失本程序作者与团队概不负责。 + + 3.14 未经书面许可禁止将本项目代码商用。 + +本软件由版权持有人和贡献者“按原样”提供,不承担任何明示或暗示的保证,包括但不限于对 +适销性和适合特定目的的暗示保证。在任何情况下,版权持有人或贡献者均不对任何直接、间 +接、附带、特殊、惩戒性或后果性损害(包括但不限于,购买替代商品或服务;损失:失去使用 +、数据或利润;(或业务中断),无论如何造成的,以及根据任何责任理论,无论是合同责任, +严格责任,还是侵权行为(包括疏忽或其他),即使被告知该等损害的可能性,也会因使用本 +软件而以任何方式产生。 diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index cd2e836..cc84483 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -1,4 +1,4 @@ - + netstandard2.1;net6.0;net8.0;net9.0 @@ -37,10 +37,6 @@ Remove direct inheritance/derivation of the ICache interface and instead use abs - - True - \ - True \ @@ -51,4 +47,11 @@ Remove direct inheritance/derivation of the ICache interface and instead use abs + + + True + \ + + + From be42d7ae425fe123645aabf9739a0efb28bcfeea Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sat, 28 Dec 2024 15:40:59 +0800 Subject: [PATCH 27/52] =?UTF-8?q?docs:=20=E4=BF=AE=E6=AD=A3=E7=89=88?= =?UTF-8?q?=E6=9D=83=E8=AE=B8=E5=8F=AF=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LICENSE | 2 +- LICENSE_CN | 2 +- TYLDDB/LICENSE | 2 +- TYLDDB/LICENSE_CN | 2 +- TYLDDB/TYLDDB.csproj | 16 ++++++++-------- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/LICENSE b/LICENSE index afa0540..4faacbe 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Change the License based on BSD 3-Clause +BSD 3-Clause License (Modified) Copyright (c) 2024, Tsing Yi Local Distributed Database diff --git a/LICENSE_CN b/LICENSE_CN index b3a735f..295e1a1 100644 --- a/LICENSE_CN +++ b/LICENSE_CN @@ -1,4 +1,4 @@ -基于 BSD 3-Clause License 修改 +BSD 3-Clause License (修改版) Copyright (c) 2024, Tsing Yi Local Distributed Database diff --git a/TYLDDB/LICENSE b/TYLDDB/LICENSE index afa0540..4faacbe 100644 --- a/TYLDDB/LICENSE +++ b/TYLDDB/LICENSE @@ -1,4 +1,4 @@ -Change the License based on BSD 3-Clause +BSD 3-Clause License (Modified) Copyright (c) 2024, Tsing Yi Local Distributed Database diff --git a/TYLDDB/LICENSE_CN b/TYLDDB/LICENSE_CN index b3a735f..295e1a1 100644 --- a/TYLDDB/LICENSE_CN +++ b/TYLDDB/LICENSE_CN @@ -1,4 +1,4 @@ -基于 BSD 3-Clause License 修改 +BSD 3-Clause License (修改版) Copyright (c) 2024, Tsing Yi Local Distributed Database diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index cc84483..92eb711 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -12,7 +12,7 @@ https://github.com/TYLDDB/TYLDDB-CSharp git ttypdb.qingyi-studio.top - BSD 3-Clause License + BSD 3-Clause License (Modified) A strongly typed constrained distributed file system that can act as a database. True True @@ -26,6 +26,8 @@ Remove direct inheritance/derivation of the ICache interface and instead use abs + + @@ -34,6 +36,11 @@ Remove direct inheritance/derivation of the ICache interface and instead use abs True \
+ + True + \ + +
@@ -47,11 +54,4 @@ Remove direct inheritance/derivation of the ICache interface and instead use abs - - - True - \ - - - From 42cf92d8805bd4a898390ef8def18d13c2d84f0f Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sat, 28 Dec 2024 15:41:32 +0800 Subject: [PATCH 28/52] =?UTF-8?q?docs:=20=E5=88=A0=E9=99=A4=E6=97=A7?= =?UTF-8?q?=E7=9A=84=E5=8F=91=E8=A1=8C=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.csproj | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index 92eb711..fd60d0a 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -19,8 +19,7 @@ DataBase QingYi-Studio README.md - Remove support for .netstandard 2.0. -Remove direct inheritance/derivation of the ICache interface and instead use abstract class relays, using virtual methods to trim asynchronous code in part of the concurrent dictionary. + From 91a965fb4266516058dc9ca49510d03049af60c9 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sat, 28 Dec 2024 15:55:57 +0800 Subject: [PATCH 29/52] =?UTF-8?q?docs:=20=E4=BC=98=E5=8C=96=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.cs | 8 +++- TYLDDB/Utils/FastCache/ICache.cs | 39 +++++++++++-------- TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs | 18 +++++---- 3 files changed, 38 insertions(+), 27 deletions(-) diff --git a/TYLDDB/TYLDDB.cs b/TYLDDB/TYLDDB.cs index 359ce37..c268361 100644 --- a/TYLDDB/TYLDDB.cs +++ b/TYLDDB/TYLDDB.cs @@ -2,11 +2,13 @@ using System.Collections.Generic; using TYLDDB.Basic; using TYLDDB.Utils; +using TYLDDB.Utils.FastCache; namespace TYLDDB { /// - /// The core class of the database. + /// The core class of the database.
+ /// 数据库的核心类。 ///
public class LDDB { @@ -16,7 +18,7 @@ public class LDDB /// public LDDB() { - // TODO + // NOTHING HERE! } ///////////////////////////////////////////////////// 私有字段 @@ -27,6 +29,8 @@ public LDDB() private bool _isRead = false; // 是否已调用读取文件 private event Action OnFileReadComplete; private Database database = new Database(); + private Cache cdCache = new ConcurrentDictionary(); + private Cache stlCache = new SemaphoreThreadLock(); ///////////////////////////////////////////////////// 公开字段 /// diff --git a/TYLDDB/Utils/FastCache/ICache.cs b/TYLDDB/Utils/FastCache/ICache.cs index 76561be..ea3ecce 100644 --- a/TYLDDB/Utils/FastCache/ICache.cs +++ b/TYLDDB/Utils/FastCache/ICache.cs @@ -42,44 +42,49 @@ public interface ICache Task> GetKeysByValueAsync(string value); /// - /// 同步方法:设置一个键值对。 + /// Set a key-value pair.
+ /// 设置一个键值对。 ///
- /// - /// - /// + /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功。
bool Set(string key, string value); /// - /// 异步方法:设置一个键值对。 + /// Set a key-value pair.
+ /// 设置一个键值对。 ///
- /// - /// - /// + /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功。
Task SetAsync(string key, string value); /// - /// 同步方法:移除一个键值对。 + /// Remove a key-value pair.
+ /// 移除一个键值对。 ///
- /// - /// + /// Key
键 + /// Whether the removal was successful or not.
是否移除成功。
bool RemoveByKey(string key); /// - /// 异步方法:移除一个键值对。 + /// Remove a key-value pair.
+ /// 移除一个键值对。 ///
- /// - /// + /// Key
键 + /// Whether the removal was successful or not.
是否移除成功。
Task RemoveByKeyAsync(string key); /// - /// 同步方法:清空缓存。 + /// Clear the cache.
+ /// 清空缓存。 ///
void Clear(); /// - /// 异步方法:清空缓存。 + /// Clear the cache.
+ /// 清空缓存。 ///
- /// Task ClearAsync(); /// diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs index 20c9e8f..c7ff0a5 100644 --- a/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs @@ -103,11 +103,12 @@ public override async Task> GetKeysByValueAsync(string value) } /// - /// 同步方法:设置一个键值对。 + /// Set a key-value pair.
+ /// 设置一个键值对。 ///
- /// - /// - /// + /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
public override bool Set(string key, string value) { lock (semaphore) @@ -129,11 +130,12 @@ public override bool Set(string key, string value) } /// - /// 异步方法:设置一个键值对。 + /// Set a key-value pair.
+ /// 设置一个键值对。 ///
- /// - /// - /// + /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
public override async Task SetAsync(string key, string value) { await semaphore.WaitAsync(); From 70213e7cb509ebc0758d138658fa916c763833b6 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sat, 28 Dec 2024 15:56:41 +0800 Subject: [PATCH 30/52] =?UTF-8?q?docs:=20=E6=9B=B4=E6=96=B0=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index fd60d0a..cec5dac 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -4,7 +4,7 @@ netstandard2.1;net6.0;net8.0;net9.0 True TYLDDB.NET - 1.0.0-alpha.2r + 1.0.0-alpha.3 TYLDDB-Project LICENSE True From 4cdb9168084d9e69d9c51ef2c3becd965c4be5ab Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sat, 28 Dec 2024 16:18:06 +0800 Subject: [PATCH 31/52] =?UTF-8?q?test:=20=E8=AE=BE=E7=BD=AE=E5=8D=95?= =?UTF-8?q?=E7=8B=AC=E7=9A=84=E7=B1=BB=E6=9D=A5=E8=BF=9B=E8=A1=8C=E6=97=B6?= =?UTF-8?q?=E9=97=B4=E6=B5=8B=E8=AF=95=EF=BC=8C=E8=80=8C=E4=B8=8D=E6=98=AF?= =?UTF-8?q?=E5=BE=88=E5=A4=9A=E4=B8=80=E6=A0=B7=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB.Test/Program.cs | 6 +-- .../HighPrecisionTimer.cs | 44 ------------------- TYLDDB.Utils.FastCache.Test/Program.cs | 6 +-- .../HighPrecisionTimer.cs | 26 ++++++++--- TimeRecord/TimeRecord.csproj | 9 ++++ 5 files changed, 34 insertions(+), 57 deletions(-) delete mode 100644 TYLDDB.Utils.FastCache.Test/HighPrecisionTimer.cs rename {TYLDDB.Test => TimeRecord}/HighPrecisionTimer.cs (55%) create mode 100644 TimeRecord/TimeRecord.csproj diff --git a/TYLDDB.Test/Program.cs b/TYLDDB.Test/Program.cs index b4583a7..f727e38 100644 --- a/TYLDDB.Test/Program.cs +++ b/TYLDDB.Test/Program.cs @@ -1,10 +1,10 @@ -using TYLDDB; -using TYLDDB.Test; +using TimeRecord; +using TYLDDB; string dbFilePath = "./example.lddb"; ///////////////////////////////////////////////////////////////////////////////////////////////////////// 实例化 -LDDB lddb = new LDDB(); +var lddb = new LDDB(); ///////////////////////////////////////////////////////////////////////////////////////////////////////// 读取文件 HighPrecisionTimer readDbTimer = new(); // 从发起读取文件到成功读取的总时间 diff --git a/TYLDDB.Utils.FastCache.Test/HighPrecisionTimer.cs b/TYLDDB.Utils.FastCache.Test/HighPrecisionTimer.cs deleted file mode 100644 index 7856bfe..0000000 --- a/TYLDDB.Utils.FastCache.Test/HighPrecisionTimer.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Diagnostics; - -namespace TYLDDB.Utils.FastCache.Test -{ - internal class HighPrecisionTimer - { - private Stopwatch stopwatch; - - public HighPrecisionTimer() - { - stopwatch = new Stopwatch(); - } - - // 启动计时器 - public void Start() - { - stopwatch.Start(); - } - - // 停止计时器 - public void Stop() - { - stopwatch.Stop(); - } - - // 重置计时器 - public void Reset() - { - stopwatch.Reset(); - } - - // 获取已用时间(毫秒) - public double ElapsedMilliseconds() - { - return stopwatch.Elapsed.TotalMilliseconds; - } - - // 获取已用时间(秒) - public double ElapsedSeconds() - { - return stopwatch.Elapsed.TotalSeconds; - } - } -} diff --git a/TYLDDB.Utils.FastCache.Test/Program.cs b/TYLDDB.Utils.FastCache.Test/Program.cs index 1b06543..5172226 100644 --- a/TYLDDB.Utils.FastCache.Test/Program.cs +++ b/TYLDDB.Utils.FastCache.Test/Program.cs @@ -1,5 +1,5 @@ +using TimeRecord; using TYLDDB.Utils.FastCache; -using TYLDDB.Utils.FastCache.Test; Console.WriteLine("基于信号量的缓存读写运行"); SemaphoreSlimDefault(); @@ -21,7 +21,7 @@ static async void SemaphoreSlimDefault() var getAllCacheTime = new HighPrecisionTimer(); var getAllCacheAsyncTime = new HighPrecisionTimer(); - ICache cache = new SemaphoreThreadLock(); + var cache = new SemaphoreThreadLock(); setTime.Start(); cache.Set("TESTKEY1", "TESTVALUE1"); @@ -91,7 +91,7 @@ static async void ConcurrentDictionary() var getAllCacheTime = new HighPrecisionTimer(); var getAllCacheAsyncTime = new HighPrecisionTimer(); - ICache cache = new ConcurrentDictionary(); + var cache = new ConcurrentDictionary(); setTime.Start(); cache.Set("TESTKEY1", "TESTVALUE1"); diff --git a/TYLDDB.Test/HighPrecisionTimer.cs b/TimeRecord/HighPrecisionTimer.cs similarity index 55% rename from TYLDDB.Test/HighPrecisionTimer.cs rename to TimeRecord/HighPrecisionTimer.cs index 820804a..352b977 100644 --- a/TYLDDB.Test/HighPrecisionTimer.cs +++ b/TimeRecord/HighPrecisionTimer.cs @@ -1,8 +1,8 @@ using System.Diagnostics; -namespace TYLDDB.Test +namespace TimeRecord { - internal class HighPrecisionTimer + public class HighPrecisionTimer { private Stopwatch stopwatch; @@ -11,31 +11,43 @@ public HighPrecisionTimer() stopwatch = new Stopwatch(); } - // 启动计时器 + /// + /// 启动计时器 + /// public void Start() { stopwatch.Start(); } - // 停止计时器 + /// + /// 停止计时器 + /// public void Stop() { stopwatch.Stop(); } - // 重置计时器 + /// + /// 重置计时器 + /// public void Reset() { stopwatch.Reset(); } - // 获取已用时间(毫秒) + /// + /// 获取已用时间(毫秒) + /// + /// public double ElapsedMilliseconds() { return stopwatch.Elapsed.TotalMilliseconds; } - // 获取已用时间(秒) + /// + /// 获取已用时间(秒) + /// + /// public double ElapsedSeconds() { return stopwatch.Elapsed.TotalSeconds; diff --git a/TimeRecord/TimeRecord.csproj b/TimeRecord/TimeRecord.csproj new file mode 100644 index 0000000..fa71b7a --- /dev/null +++ b/TimeRecord/TimeRecord.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + From ddbb9ba33dea29cb669cd2580c3b3d67e8064bc2 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sat, 28 Dec 2024 16:18:43 +0800 Subject: [PATCH 32/52] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E5=86=99?= =?UTF-8?q?=E5=85=A5=E6=96=87=E4=BB=B6=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/Utils/Writer.cs | 104 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 102 insertions(+), 2 deletions(-) diff --git a/TYLDDB/Utils/Writer.cs b/TYLDDB/Utils/Writer.cs index 75e8674..17adbfa 100644 --- a/TYLDDB/Utils/Writer.cs +++ b/TYLDDB/Utils/Writer.cs @@ -1,10 +1,110 @@ -namespace TYLDDB.Utils +using System; +using System.IO; +using System.Text; +using System.Threading.Tasks; + +namespace TYLDDB.Utils { /// /// A class used to write contents into the file
/// 用于写入文件的类 ///
- public class Writer + public struct Writer { + // 同步写入大字符串到文件 + public static void WriteStringToFile(string filePath, string content, bool append = false) + { + // 使用64KB的缓冲区 + int bufferSize = 64 * 1024; // 64KB 缓冲区 + + // 确保文件路径所在的目录存在 + string directory = Path.GetDirectoryName(filePath); + if (!Directory.Exists(directory)) + { + Directory.CreateDirectory(directory); + } + + // 使用StreamWriter并指定缓冲区大小 + using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8, bufferSize)) + { + writer.Write(content); + } + } + + // 异步写入大字符串到文件 + public static async Task WriteStringToFileAsync(string filePath, string content, bool append = false) + { + // 使用64KB的缓冲区 + int bufferSize = 64 * 1024; // 64KB 缓冲区 + + // 确保文件路径所在的目录存在 + string directory = Path.GetDirectoryName(filePath); + if (!Directory.Exists(directory)) + { + Directory.CreateDirectory(directory); + } + + // 使用StreamWriter并指定缓冲区大小 + using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8, bufferSize)) + { + // 异步写入内容 + await writer.WriteAsync(content); + } + } + + // 分块写入大字符串到文件 + public static void WriteStringToFileInChunks(string filePath, string content, int chunkSize = 64 * 1024) + { + // 确保文件路径所在的目录存在 + string directory = Path.GetDirectoryName(filePath); + if (!Directory.Exists(directory)) + { + Directory.CreateDirectory(directory); + } + + using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8, 64 * 1024)) + { + int totalLength = content.Length; + int offset = 0; + + while (offset < totalLength) + { + int length = Math.Min(chunkSize, totalLength - offset); + writer.Write(content.Substring(offset, length)); + offset += length; + } + } + } + + // 分块写入大字符串到文件 + public static async Task WriteStringToFileInChunksAsync(string filePath, string content, int chunkSize = 64 * 1024, bool append = false) + { + // 确保文件路径所在的目录存在 + string directory = Path.GetDirectoryName(filePath); + if (!Directory.Exists(directory)) + { + Directory.CreateDirectory(directory); + } + + using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8, 64 * 1024)) + { + int totalLength = content.Length; + int offset = 0; + + // 分块写入文件 + while (offset < totalLength) + { + // 计算当前块的大小 + int length = Math.Min(chunkSize, totalLength - offset); + string chunk = content.Substring(offset, length); + + // 异步写入当前块 + await writer.WriteAsync(chunk); + + // 更新偏移量 + offset += length; + } + } + } } } From 0a423042b3c7bbc68d479d55cc9554e7a1167076 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sat, 28 Dec 2024 16:42:31 +0800 Subject: [PATCH 33/52] =?UTF-8?q?test:=20=E5=86=99=E5=85=A5=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E7=9A=84=E6=B5=8B=E8=AF=95=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB-CSharp.sln | 14 +++++++ TYLDDB.Test/TYLDDB.Test.csproj | 1 + .../TYLDDB.Utils.FastCache.Test.csproj | 1 + TYLDDB.Utils.Writer.Test/Program.cs | 37 +++++++++++++++++++ .../TYLDDB.Utils.Writer.Test.csproj | 15 ++++++++ 5 files changed, 68 insertions(+) create mode 100644 TYLDDB.Utils.Writer.Test/Program.cs create mode 100644 TYLDDB.Utils.Writer.Test/TYLDDB.Utils.Writer.Test.csproj diff --git a/TYLDDB-CSharp.sln b/TYLDDB-CSharp.sln index 9ed67ba..fb901c4 100644 --- a/TYLDDB-CSharp.sln +++ b/TYLDDB-CSharp.sln @@ -16,6 +16,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TYLDDB.Utils.FastCache.Test EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TYLDDB.Utils.Writer.Test", "TYLDDB.Utils.Writer.Test\TYLDDB.Utils.Writer.Test.csproj", "{1BA4CC53-078F-4943-B8EF-A522DA9E5060}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TimeRecord", "TimeRecord\TimeRecord.csproj", "{F95CF6BC-2255-47F8-AAB3-B7812BB2894D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -34,6 +38,14 @@ Global {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B}.Debug|Any CPU.Build.0 = Debug|Any CPU {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B}.Release|Any CPU.ActiveCfg = Release|Any CPU {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B}.Release|Any CPU.Build.0 = Release|Any CPU + {1BA4CC53-078F-4943-B8EF-A522DA9E5060}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1BA4CC53-078F-4943-B8EF-A522DA9E5060}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1BA4CC53-078F-4943-B8EF-A522DA9E5060}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1BA4CC53-078F-4943-B8EF-A522DA9E5060}.Release|Any CPU.Build.0 = Release|Any CPU + {F95CF6BC-2255-47F8-AAB3-B7812BB2894D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F95CF6BC-2255-47F8-AAB3-B7812BB2894D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F95CF6BC-2255-47F8-AAB3-B7812BB2894D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F95CF6BC-2255-47F8-AAB3-B7812BB2894D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -41,6 +53,8 @@ Global GlobalSection(NestedProjects) = preSolution {FDFD566C-CB13-43EB-970E-0EC0A21E36C0} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} + {1BA4CC53-078F-4943-B8EF-A522DA9E5060} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} + {F95CF6BC-2255-47F8-AAB3-B7812BB2894D} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {19390089-354C-41AD-AF7D-9FB3998A88EA} diff --git a/TYLDDB.Test/TYLDDB.Test.csproj b/TYLDDB.Test/TYLDDB.Test.csproj index 8afa4b0..1f5fc44 100644 --- a/TYLDDB.Test/TYLDDB.Test.csproj +++ b/TYLDDB.Test/TYLDDB.Test.csproj @@ -8,6 +8,7 @@ + diff --git a/TYLDDB.Utils.FastCache.Test/TYLDDB.Utils.FastCache.Test.csproj b/TYLDDB.Utils.FastCache.Test/TYLDDB.Utils.FastCache.Test.csproj index bb48fc4..700866e 100644 --- a/TYLDDB.Utils.FastCache.Test/TYLDDB.Utils.FastCache.Test.csproj +++ b/TYLDDB.Utils.FastCache.Test/TYLDDB.Utils.FastCache.Test.csproj @@ -8,6 +8,7 @@ + diff --git a/TYLDDB.Utils.Writer.Test/Program.cs b/TYLDDB.Utils.Writer.Test/Program.cs new file mode 100644 index 0000000..2e269e1 --- /dev/null +++ b/TYLDDB.Utils.Writer.Test/Program.cs @@ -0,0 +1,37 @@ +using TimeRecord; +using TYLDDB.Utils; + +string largeString = new('A', 1); +string syncFilePath = "sync.txt"; +string asyncFilePath = "async.txt"; +string syncChunkFilePath = "sync-chunk.txt"; +string asyncChunkFilePath = "async-chunk.txt"; + +var syncTime = new HighPrecisionTimer(); +var asyncTime = new HighPrecisionTimer(); +var syncChunkTime = new HighPrecisionTimer(); +var asyncChunkTime = new HighPrecisionTimer(); + +syncTime.Start(); +Writer.WriteStringToFile(syncFilePath, largeString); +syncTime.Stop(); + +asyncTime.Start(); +await Writer.WriteStringToFileAsync(asyncFilePath, largeString); +asyncTime.Stop(); + +syncChunkTime.Start(); +Writer.WriteStringToFileInChunks(syncChunkFilePath, largeString); +syncChunkTime.Stop(); + +asyncChunkTime.Start(); +await Writer.WriteStringToFileInChunksAsync(asyncChunkFilePath, largeString); +asyncChunkTime.Stop(); + +Console.WriteLine("测试结果:"); +Console.WriteLine($"同步写入:{syncTime.ElapsedMilliseconds()}ms"); +Console.WriteLine($"异步写入:{asyncTime.ElapsedMilliseconds()}ms"); +Console.WriteLine($"同步分块写入:{syncChunkTime.ElapsedMilliseconds()}ms"); +Console.WriteLine($"异步分块写入:{asyncChunkTime.ElapsedMilliseconds()}ms"); + +Console.ReadLine(); diff --git a/TYLDDB.Utils.Writer.Test/TYLDDB.Utils.Writer.Test.csproj b/TYLDDB.Utils.Writer.Test/TYLDDB.Utils.Writer.Test.csproj new file mode 100644 index 0000000..700866e --- /dev/null +++ b/TYLDDB.Utils.Writer.Test/TYLDDB.Utils.Writer.Test.csproj @@ -0,0 +1,15 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + From c91cbf40c3b247e7ded412a2a61d373d61e53fde Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sun, 29 Dec 2024 17:07:26 +0800 Subject: [PATCH 34/52] =?UTF-8?q?refactor:=20=E7=AE=80=E5=8C=96using?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/Utils/Writer.cs | 146 +++++++++++++++++++++-------------------- 1 file changed, 75 insertions(+), 71 deletions(-) diff --git a/TYLDDB/Utils/Writer.cs b/TYLDDB/Utils/Writer.cs index 17adbfa..2f15b1b 100644 --- a/TYLDDB/Utils/Writer.cs +++ b/TYLDDB/Utils/Writer.cs @@ -6,104 +6,108 @@ namespace TYLDDB.Utils { /// - /// A class used to write contents into the file
- /// 用于写入文件的类 + /// A class used to write contents into the file. + /// Suitable for writing to slower hard drives, such as mechanical hard drives. + /// Suitable for asynchronously writing to slow hard drives, such as mechanical hard drives. + /// Ideal for writing to fast hard drives, such as solid state drives. + /// Ideal for asynchronously writing content in faster hard drives, such as solid state drives. + /// 用于写入文件的类。 + /// 适用于在较慢的硬盘中写入内容,如机械硬盘。 + /// 适用于在较慢的硬盘中异步写入内容,如机械硬盘。 + /// 适用于在较快的硬盘中写入内容,如固态硬盘。 + /// 适用于在较快的硬盘中异步写入内容,如固态硬盘。 ///
public struct Writer { - // 同步写入大字符串到文件 - public static void WriteStringToFile(string filePath, string content, bool append = false) + /// + /// Write large strings to a file synchronously.
+ /// 同步写入大字符串到文件。 + ///
+ /// File path
文件路径 + /// Written content
写入的内容 + public static void WriteStringToFile(string filePath, string content) { // 使用64KB的缓冲区 int bufferSize = 64 * 1024; // 64KB 缓冲区 - // 确保文件路径所在的目录存在 - string directory = Path.GetDirectoryName(filePath); - if (!Directory.Exists(directory)) - { - Directory.CreateDirectory(directory); - } - - // 使用StreamWriter并指定缓冲区大小 - using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8, bufferSize)) - { - writer.Write(content); - } + // 使用FileStream打开文件,确保文件完全覆盖而不是追加 + using FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize); + using StreamWriter writer = new StreamWriter(fs, Encoding.UTF8, bufferSize); + // 写入内容 + writer.Write(content); } - // 异步写入大字符串到文件 - public static async Task WriteStringToFileAsync(string filePath, string content, bool append = false) + /// + /// Asynchronously writes large strings to a file.
+ /// 异步写入大字符串到文件。 + ///
+ /// File path
文件路径 + /// Written content
写入的内容 + public static async void WriteStringToFileAsync(string filePath, string content) { // 使用64KB的缓冲区 int bufferSize = 64 * 1024; // 64KB 缓冲区 - // 确保文件路径所在的目录存在 - string directory = Path.GetDirectoryName(filePath); - if (!Directory.Exists(directory)) - { - Directory.CreateDirectory(directory); - } - - // 使用StreamWriter并指定缓冲区大小 - using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8, bufferSize)) - { - // 异步写入内容 - await writer.WriteAsync(content); - } + // 使用FileStream打开文件,确保文件完全覆盖而不是追加 + using FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize); + using StreamWriter writer = new StreamWriter(fs, Encoding.UTF8, bufferSize); + // 异步写入内容 + await writer.WriteAsync(content); } - // 分块写入大字符串到文件 + /// + /// Write large strings to the file in blocks.
+ /// 分块写入大字符串到文件。 + ///
+ /// File path
文件路径 + /// Written content
写入的内容 + /// Block size
分块大小 public static void WriteStringToFileInChunks(string filePath, string content, int chunkSize = 64 * 1024) { - // 确保文件路径所在的目录存在 - string directory = Path.GetDirectoryName(filePath); - if (!Directory.Exists(directory)) - { - Directory.CreateDirectory(directory); - } - using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8, 64 * 1024)) - { - int totalLength = content.Length; - int offset = 0; + // 将字符串转换为字节数组 + byte[] contentBytes = Encoding.UTF8.GetBytes(content); - while (offset < totalLength) - { - int length = Math.Min(chunkSize, totalLength - offset); - writer.Write(content.Substring(offset, length)); - offset += length; - } + using FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, chunkSize); + using StreamWriter writer = new StreamWriter(fs, Encoding.UTF8, chunkSize); + int totalLength = contentBytes.Length; + int offset = 0; + + while (offset < totalLength) + { + int length = Math.Min(chunkSize, totalLength - offset); + writer.Write(Encoding.UTF8.GetString(contentBytes, offset, length)); + offset += length; } } - // 分块写入大字符串到文件 - public static async Task WriteStringToFileInChunksAsync(string filePath, string content, int chunkSize = 64 * 1024, bool append = false) + /// + /// Asynchronously blocks large strings to a file.
+ /// 异步分块写入大字符串到文件。 + ///
+ /// File path
文件路径 + /// Written content
写入的内容 + /// Block size
分块大小 + public static async void WriteStringToFileInChunksAsync(string filePath, string content, int chunkSize = 64 * 1024) { - // 确保文件路径所在的目录存在 - string directory = Path.GetDirectoryName(filePath); - if (!Directory.Exists(directory)) - { - Directory.CreateDirectory(directory); - } + // 将字符串转换为字节数组 + byte[] contentBytes = Encoding.UTF8.GetBytes(content); - using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8, 64 * 1024)) - { - int totalLength = content.Length; - int offset = 0; + using FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, chunkSize); + using StreamWriter writer = new StreamWriter(fs, Encoding.UTF8, chunkSize); + int totalLength = contentBytes.Length; + int offset = 0; - // 分块写入文件 - while (offset < totalLength) - { - // 计算当前块的大小 - int length = Math.Min(chunkSize, totalLength - offset); - string chunk = content.Substring(offset, length); + while (offset < totalLength) + { + int length = Math.Min(chunkSize, totalLength - offset); + string chunk = Encoding.UTF8.GetString(contentBytes, offset, length); - // 异步写入当前块 - await writer.WriteAsync(chunk); + // 异步写入当前块 + await writer.WriteAsync(chunk); - // 更新偏移量 - offset += length; - } + // 更新偏移量 + offset += length; } } } From c04c3aae4378c33eaf1db2d7acd294372cf8c7b9 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sun, 29 Dec 2024 17:52:37 +0800 Subject: [PATCH 35/52] feat: parser --- TYLDDB/Parser/Parser.cs | 90 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 TYLDDB/Parser/Parser.cs diff --git a/TYLDDB/Parser/Parser.cs b/TYLDDB/Parser/Parser.cs new file mode 100644 index 0000000..0868cff --- /dev/null +++ b/TYLDDB/Parser/Parser.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; + +namespace TYLDDB.Parser +{ + /// + /// 解析器 + /// + public class Parser + { + private string _dbContent; + + /// + /// + /// + /// Database content
数据库内容 + public Parser(string dbContent) + { + _dbContent = dbContent; + } + + // 正则表达式,用于匹配不同类型的条目 + private readonly string pattern = @"(\w+)::""([^""]+)""=""([^""]+)"";"; + + // 解析输入字符串,提取不同类型的条目 + private Dictionary Parse(string input) + { + // 字典存储最终的解析结果 + Dictionary parsedData = new Dictionary(); + + // 使用正则表达式查找所有匹配项 + MatchCollection matches = Regex.Matches(input, pattern); + + // 遍历所有匹配项,添加到字典 + foreach (Match match in matches) + { + string typeName = match.Groups[1].Value; // 类型名称(如string, int) + string varName = match.Groups[2].Value; // 变量名称(如str_name) + string value = match.Groups[3].Value; // 变量值(如name1) + + Type type = GetTypeFromString(typeName); // 获取对应的类型 + + // 将名称和类型添加到字典 + if (type != null) + { + parsedData.Add(varName, type); + } + } + + return parsedData; + } + + // 根据类型名称返回对应的 .NET 类型 + private static Type GetTypeFromString(string typeName) + { + switch (typeName.ToLower()) + { + case "string": + return typeof(string); + case "int": + return typeof(int); + case "short": + return typeof(short); + case "long": + return typeof(long); + case "float": + return typeof(float); + case "double": + return typeof(double); + case "boolean": + return typeof(bool); + case "char": + return typeof(char); + case "decimal": + return typeof(decimal); + default: + return typeof(string); // 如果未识别的类型,返回 string + } + } + + public void Strings() + { + } + + public void Integers() + { + } + } +} From 9f2c01043e3fa28fa100b0aace8f19488321b47e Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sun, 29 Dec 2024 19:06:16 +0800 Subject: [PATCH 36/52] feat: rewrite parser --- TYLDDB-CSharp.sln | 7 + TYLDDB.Parser.Test/Program.cs | 33 ++ TYLDDB.Parser.Test/TYLDDB.Parser.Test.csproj | 15 + TYLDDB.Test/example.lddb | 14 +- TYLDDB/Parser/Parser.cs | 392 ++++++++++++++++--- TYLDDB/TYLDDB.csproj | 4 - 6 files changed, 406 insertions(+), 59 deletions(-) create mode 100644 TYLDDB.Parser.Test/Program.cs create mode 100644 TYLDDB.Parser.Test/TYLDDB.Parser.Test.csproj diff --git a/TYLDDB-CSharp.sln b/TYLDDB-CSharp.sln index fb901c4..d409f8a 100644 --- a/TYLDDB-CSharp.sln +++ b/TYLDDB-CSharp.sln @@ -20,6 +20,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TYLDDB.Utils.Writer.Test", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TimeRecord", "TimeRecord\TimeRecord.csproj", "{F95CF6BC-2255-47F8-AAB3-B7812BB2894D}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TYLDDB.Parser.Test", "TYLDDB.Parser.Test\TYLDDB.Parser.Test.csproj", "{0B96CCF3-16C7-4B18-9D07-A19D5D8E9641}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -46,6 +48,10 @@ Global {F95CF6BC-2255-47F8-AAB3-B7812BB2894D}.Debug|Any CPU.Build.0 = Debug|Any CPU {F95CF6BC-2255-47F8-AAB3-B7812BB2894D}.Release|Any CPU.ActiveCfg = Release|Any CPU {F95CF6BC-2255-47F8-AAB3-B7812BB2894D}.Release|Any CPU.Build.0 = Release|Any CPU + {0B96CCF3-16C7-4B18-9D07-A19D5D8E9641}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0B96CCF3-16C7-4B18-9D07-A19D5D8E9641}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0B96CCF3-16C7-4B18-9D07-A19D5D8E9641}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0B96CCF3-16C7-4B18-9D07-A19D5D8E9641}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -55,6 +61,7 @@ Global {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} {1BA4CC53-078F-4943-B8EF-A522DA9E5060} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} {F95CF6BC-2255-47F8-AAB3-B7812BB2894D} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} + {0B96CCF3-16C7-4B18-9D07-A19D5D8E9641} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {19390089-354C-41AD-AF7D-9FB3998A88EA} diff --git a/TYLDDB.Parser.Test/Program.cs b/TYLDDB.Parser.Test/Program.cs new file mode 100644 index 0000000..fc62551 --- /dev/null +++ b/TYLDDB.Parser.Test/Program.cs @@ -0,0 +1,33 @@ +using TimeRecord; +using TYLDDB.Parser; + +string content = @" +string::""str_name""=""name1""; +int::""int_value""=""123""; +short::""short_value""=""32767""; +long::""long_value""=""2147483647""; +float::""float_value""=""3.14f""; +double::""double_value""=""3.141592653589793""; +boolean::""bool""=""true""; +char::""char_value""=""127""; +decimal::decima_value = 19.99m""; +internaldb::""db_name""={}; +"; + +var parser = new Parser(); +var time = new HighPrecisionTimer(); +time.Start(); +// 调用 Parse 方法进行解析 +var result = Parser.ParseString(content); +time.Stop(); +// 输出找到的所有键值对 +if (result.Count > 0) +{ + foreach (var entry in result) + { + Console.WriteLine($"{entry.Key}: {entry.Value}"); + } +} + +Console.WriteLine($"Time: {time.ElapsedMilliseconds()}ms"); +Console.ReadLine(); \ No newline at end of file diff --git a/TYLDDB.Parser.Test/TYLDDB.Parser.Test.csproj b/TYLDDB.Parser.Test/TYLDDB.Parser.Test.csproj new file mode 100644 index 0000000..700866e --- /dev/null +++ b/TYLDDB.Parser.Test/TYLDDB.Parser.Test.csproj @@ -0,0 +1,15 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + diff --git a/TYLDDB.Test/example.lddb b/TYLDDB.Test/example.lddb index 6f6b19e..d895a31 100644 --- a/TYLDDB.Test/example.lddb +++ b/TYLDDB.Test/example.lddb @@ -1,13 +1,13 @@ database1::{ string::"str_name"="name1"; - int::"int_value"="123" - short::"short_value"="32767" + int::"int_value"="123"; + short::"short_value"="32767"; long::"long_value"="2147483647"; - float::"float_value"="3.14f" - double::"double_value"="3.141592653589793" - boolean::"bool"="true" - char::"char_value"="127" - decimal::decima_value = 19.99m" + float::"float_value"="3.14f"; + double::"double_value"="3.141592653589793"; + boolean::"bool"="true"; + char::"char_value"="127"; + decimal::decima_value = 19.99m"; internaldb::"db_name"={}; distributeddb::"distributed_db_name"="./example.lddb"; }; diff --git a/TYLDDB/Parser/Parser.cs b/TYLDDB/Parser/Parser.cs index 0868cff..326f561 100644 --- a/TYLDDB/Parser/Parser.cs +++ b/TYLDDB/Parser/Parser.cs @@ -5,86 +5,382 @@ namespace TYLDDB.Parser { /// - /// 解析器 + /// Data type parser.
+ /// 数据类型解析器。 ///
public class Parser { - private string _dbContent; + // 定义正则表达式来匹配键值对(类型::"key"="value") + private readonly static string pattern = @"(?<=^|\s)(\w+)\s*::\s*""([^""]+)"""; /// - /// + /// Parses the given content and finds all matching key-value pairs.
+ /// 解析给定的内容并查找所有匹配的键值对。 ///
- /// Database content
数据库内容 - public Parser(string dbContent) + /// The content string to be parsed, containing key-value pairs.
要解析的内容字符串,包含键值对。 + /// A dictionary containing all matched key-value pairs. If no matching key-value pair is found, an empty dictionary is returned.
包含所有匹配的键值对的字典。如果没有找到匹配的键值对,返回空字典。
+ public static Dictionary ParseString(string content) { - _dbContent = dbContent; + string type = "string"; + + // 创建一个字典来存储找到的所有键值对 + var result = new Dictionary(); + + // 匹配整个内容中的所有键值对 + var matches = Regex.Matches(content, pattern); + + // 遍历所有的匹配项 + foreach (Match match in matches) + { + string matchedKey = match.Groups[1].Value; + string matchedValue = match.Groups[2].Value; + + // 如果提供的类型与键的类型匹配,加入到结果字典 + if (string.Equals(type, matchedKey, StringComparison.OrdinalIgnoreCase)) + { + // 将匹配的键值对添加到字典中 + result[matchedKey] = matchedValue; + } + } + + // 返回结果字典,若没有匹配项则返回空字典 + return result; } - // 正则表达式,用于匹配不同类型的条目 - private readonly string pattern = @"(\w+)::""([^""]+)""=""([^""]+)"";"; + /// + /// Parses the given content and finds all matching key-value pairs.
+ /// 解析给定的内容并查找所有匹配的键值对。 + ///
+ /// The content string to be parsed, containing key-value pairs.
要解析的内容字符串,包含键值对。 + /// A dictionary containing all matched key-value pairs. If no matching key-value pair is found, an empty dictionary is returned.
包含所有匹配的键值对的字典。如果没有找到匹配的键值对,返回空字典。
+ public static Dictionary ParseInt(string content) + { + string type = "int"; // 目标类型是 int + + // 创建一个字典来存储找到的所有键值对 + var result = new Dictionary(); - // 解析输入字符串,提取不同类型的条目 - private Dictionary Parse(string input) + // 匹配整个内容中的所有键值对 + var matches = Regex.Matches(content, pattern); + + // 遍历所有的匹配项 + foreach (Match match in matches) + { + string matchedKey = match.Groups[1].Value; + string matchedValue = match.Groups[2].Value; + + // 如果提供的类型与键的类型匹配 + if (string.Equals(type, matchedKey, StringComparison.OrdinalIgnoreCase)) + { + // 尝试将值转换为 int 类型 + if (int.TryParse(matchedValue, out int intValue)) + { + // 将匹配的键值对添加到字典中 + result[matchedKey] = intValue; + } + else + { + throw new Exception($"无法将值 \"{matchedValue}\" 转换为 int。"); + } + } + } + + // 返回结果字典,若没有匹配项则返回空字典 + return result; + } + + /// + /// Parses the given content and finds all matching key-value pairs.
+ /// 解析给定的内容并查找所有匹配的键值对。 + ///
+ /// The content string to be parsed, containing key-value pairs.
要解析的内容字符串,包含键值对。 + /// A dictionary containing all matched key-value pairs. If no matching key-value pair is found, an empty dictionary is returned.
包含所有匹配的键值对的字典。如果没有找到匹配的键值对,返回空字典。
+ public static Dictionary ParseShort(string content) { - // 字典存储最终的解析结果 - Dictionary parsedData = new Dictionary(); + string type = "short"; // 目标类型是 short + + // 创建一个字典来存储找到的所有键值对 + var result = new Dictionary(); - // 使用正则表达式查找所有匹配项 - MatchCollection matches = Regex.Matches(input, pattern); + // 匹配整个内容中的所有键值对 + var matches = Regex.Matches(content, pattern); - // 遍历所有匹配项,添加到字典 + // 遍历所有的匹配项 foreach (Match match in matches) { - string typeName = match.Groups[1].Value; // 类型名称(如string, int) - string varName = match.Groups[2].Value; // 变量名称(如str_name) - string value = match.Groups[3].Value; // 变量值(如name1) + string matchedKey = match.Groups[1].Value; + string matchedValue = match.Groups[2].Value; - Type type = GetTypeFromString(typeName); // 获取对应的类型 + // 如果提供的类型与键的类型匹配 + if (string.Equals(type, matchedKey, StringComparison.OrdinalIgnoreCase)) + { + // 尝试将值转换为 short 类型 + if (short.TryParse(matchedValue, out short shortValue)) + { + // 将匹配的键值对添加到字典中 + result[matchedKey] = shortValue; + } + else + { + throw new Exception($"无法将值 \"{matchedValue}\" 转换为 short。"); + } + } + } + + // 返回结果字典,若没有匹配项则返回空字典 + return result; + } + + /// + /// Parses the given content and finds all matching key-value pairs.
+ /// 解析给定的内容并查找所有匹配的键值对。 + ///
+ /// The content string to be parsed, containing key-value pairs.
要解析的内容字符串,包含键值对。 + /// A dictionary containing all matched key-value pairs. If no matching key-value pair is found, an empty dictionary is returned.
包含所有匹配的键值对的字典。如果没有找到匹配的键值对,返回空字典。
+ public static Dictionary ParseLong(string content) + { + string type = "long"; // 目标类型是 long + + // 创建一个字典来存储找到的所有键值对 + var result = new Dictionary(); + + // 匹配整个内容中的所有键值对 + var matches = Regex.Matches(content, pattern); + + // 遍历所有的匹配项 + foreach (Match match in matches) + { + string matchedKey = match.Groups[1].Value; + string matchedValue = match.Groups[2].Value; - // 将名称和类型添加到字典 - if (type != null) + // 如果提供的类型与键的类型匹配 + if (string.Equals(type, matchedKey, StringComparison.OrdinalIgnoreCase)) { - parsedData.Add(varName, type); + // 尝试将值转换为 long 类型 + if (long.TryParse(matchedValue, out long longValue)) + { + // 将匹配的键值对添加到字典中 + result[matchedKey] = longValue; + } + else + { + throw new Exception($"无法将值 \"{matchedValue}\" 转换为 long。"); + } } } - return parsedData; + // 返回结果字典,若没有匹配项则返回空字典 + return result; } - // 根据类型名称返回对应的 .NET 类型 - private static Type GetTypeFromString(string typeName) + /// + /// Parses the given content and finds all matching key-value pairs.
+ /// 解析给定的内容并查找所有匹配的键值对。 + ///
+ /// The content string to be parsed, containing key-value pairs.
要解析的内容字符串,包含键值对。 + /// A dictionary containing all matched key-value pairs. If no matching key-value pair is found, an empty dictionary is returned.
包含所有匹配的键值对的字典。如果没有找到匹配的键值对,返回空字典。
+ public static Dictionary ParseFloat(string content) { - switch (typeName.ToLower()) + string type = "float"; // 目标类型是 float + + // 创建一个字典来存储找到的所有键值对 + var result = new Dictionary(); + + // 匹配整个内容中的所有键值对 + var matches = Regex.Matches(content, pattern); + + // 遍历所有的匹配项 + foreach (Match match in matches) { - case "string": - return typeof(string); - case "int": - return typeof(int); - case "short": - return typeof(short); - case "long": - return typeof(long); - case "float": - return typeof(float); - case "double": - return typeof(double); - case "boolean": - return typeof(bool); - case "char": - return typeof(char); - case "decimal": - return typeof(decimal); - default: - return typeof(string); // 如果未识别的类型,返回 string + string matchedKey = match.Groups[1].Value; + string matchedValue = match.Groups[2].Value; + + // 如果提供的类型与键的类型匹配 + if (string.Equals(type, matchedKey, StringComparison.OrdinalIgnoreCase)) + { + // 尝试将值转换为 short 类型 + if (float.TryParse(matchedValue, out float floatValue)) + { + // 将匹配的键值对添加到字典中 + result[matchedKey] = floatValue; + } + else + { + throw new Exception($"无法将值 \"{matchedValue}\" 转换为 float。"); + } + } } + + // 返回结果字典,若没有匹配项则返回空字典 + return result; } - public void Strings() + /// + /// Parses the given content and finds all matching key-value pairs.
+ /// 解析给定的内容并查找所有匹配的键值对。 + ///
+ /// The content string to be parsed, containing key-value pairs.
要解析的内容字符串,包含键值对。 + /// A dictionary containing all matched key-value pairs. If no matching key-value pair is found, an empty dictionary is returned.
包含所有匹配的键值对的字典。如果没有找到匹配的键值对,返回空字典。
+ public static Dictionary ParseDouble(string content) { + string type = "double"; // 目标类型是 double + + // 创建一个字典来存储找到的所有键值对 + var result = new Dictionary(); + + // 匹配整个内容中的所有键值对 + var matches = Regex.Matches(content, pattern); + + // 遍历所有的匹配项 + foreach (Match match in matches) + { + string matchedKey = match.Groups[1].Value; + string matchedValue = match.Groups[2].Value; + + // 如果提供的类型与键的类型匹配 + if (string.Equals(type, matchedKey, StringComparison.OrdinalIgnoreCase)) + { + // 尝试将值转换为 short 类型 + if (double.TryParse(matchedValue, out double Value)) + { + // 将匹配的键值对添加到字典中 + result[matchedKey] = Value; + } + else + { + throw new Exception($"无法将值 \"{matchedValue}\" 转换为 double。"); + } + } + } + + // 返回结果字典,若没有匹配项则返回空字典 + return result; + } + + /// + /// Parses the given content and finds all matching key-value pairs.
+ /// 解析给定的内容并查找所有匹配的键值对。 + ///
+ /// The content string to be parsed, containing key-value pairs.
要解析的内容字符串,包含键值对。 + /// A dictionary containing all matched key-value pairs. If no matching key-value pair is found, an empty dictionary is returned.
包含所有匹配的键值对的字典。如果没有找到匹配的键值对,返回空字典。
+ public static Dictionary ParseBoolean(string content) + { + string type = "boolean"; // 目标类型是 float + + // 创建一个字典来存储找到的所有键值对 + var result = new Dictionary(); + + // 匹配整个内容中的所有键值对 + var matches = Regex.Matches(content, pattern); + + // 遍历所有的匹配项 + foreach (Match match in matches) + { + string matchedKey = match.Groups[1].Value; + string matchedValue = match.Groups[2].Value; + + // 如果提供的类型与键的类型匹配 + if (string.Equals(type, matchedKey, StringComparison.OrdinalIgnoreCase)) + { + // 尝试将值转换为 short 类型 + if (bool.TryParse(matchedValue, out bool Value)) + { + // 将匹配的键值对添加到字典中 + result[matchedKey] = Value; + } + else + { + throw new Exception($"无法将值 \"{matchedValue}\" 转换为 bool。"); + } + } + } + + // 返回结果字典,若没有匹配项则返回空字典 + return result; + } + + /// + /// Parses the given content and finds all matching key-value pairs.
+ /// 解析给定的内容并查找所有匹配的键值对。 + ///
+ /// The content string to be parsed, containing key-value pairs.
要解析的内容字符串,包含键值对。 + /// A dictionary containing all matched key-value pairs. If no matching key-value pair is found, an empty dictionary is returned.
包含所有匹配的键值对的字典。如果没有找到匹配的键值对,返回空字典。
+ public static Dictionary ParseChar(string content) + { + string type = "char"; // 目标类型是 float + + // 创建一个字典来存储找到的所有键值对 + var result = new Dictionary(); + + // 匹配整个内容中的所有键值对 + var matches = Regex.Matches(content, pattern); + + // 遍历所有的匹配项 + foreach (Match match in matches) + { + string matchedKey = match.Groups[1].Value; + string matchedValue = match.Groups[2].Value; + + // 如果提供的类型与键的类型匹配 + if (string.Equals(type, matchedKey, StringComparison.OrdinalIgnoreCase)) + { + // 尝试将值转换为 short 类型 + if (char.TryParse(matchedValue, out char Value)) + { + // 将匹配的键值对添加到字典中 + result[matchedKey] = Value; + } + else + { + throw new Exception($"无法将值 \"{matchedValue}\" 转换为 char。"); + } + } + } + + // 返回结果字典,若没有匹配项则返回空字典 + return result; } - public void Integers() + /// + /// Parses the given content and finds all matching key-value pairs.
+ /// 解析给定的内容并查找所有匹配的键值对。 + ///
+ /// The content string to be parsed, containing key-value pairs.
要解析的内容字符串,包含键值对。 + /// A dictionary containing all matched key-value pairs. If no matching key-value pair is found, an empty dictionary is returned.
包含所有匹配的键值对的字典。如果没有找到匹配的键值对,返回空字典。
+ public static Dictionary ParseDecimal(string content) { + string type = "decimal"; // 目标类型是 float + + // 创建一个字典来存储找到的所有键值对 + var result = new Dictionary(); + + // 匹配整个内容中的所有键值对 + var matches = Regex.Matches(content, pattern); + + // 遍历所有的匹配项 + foreach (Match match in matches) + { + string matchedKey = match.Groups[1].Value; + string matchedValue = match.Groups[2].Value; + + // 如果提供的类型与键的类型匹配 + if (string.Equals(type, matchedKey, StringComparison.OrdinalIgnoreCase)) + { + // 尝试将值转换为 short 类型 + if (decimal.TryParse(matchedValue, out decimal Value)) + { + // 将匹配的键值对添加到字典中 + result[matchedKey] = Value; + } + else + { + throw new Exception($"无法将值 \"{matchedValue}\" 转换为 decimal。"); + } + } + } + + // 返回结果字典,若没有匹配项则返回空字典 + return result; } } } diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index cec5dac..ce3d791 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -49,8 +49,4 @@ - - - - From 47ab0387f72582e7969d6fded3012d889473e1aa Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Sun, 29 Dec 2024 19:09:43 +0800 Subject: [PATCH 37/52] docs: update release notes --- TYLDDB/TYLDDB.csproj | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index ce3d791..1cf8f79 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -19,7 +19,8 @@ DataBase QingYi-Studio README.md - + Add a database parser (data type only, internal and distributed databases are not available). +Fast cache underlying interface optimization. From be97a208a855e4caf96ea3bf2893fbc4e829ad72 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 30 Dec 2024 16:34:50 +0800 Subject: [PATCH 38/52] =?UTF-8?q?feat:=20=E4=BC=98=E5=8C=96=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E8=B7=AF=E5=BE=84=E8=BE=93=E5=85=A5=E9=AA=8C=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.cs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/TYLDDB/TYLDDB.cs b/TYLDDB/TYLDDB.cs index c268361..ddca467 100644 --- a/TYLDDB/TYLDDB.cs +++ b/TYLDDB/TYLDDB.cs @@ -39,11 +39,16 @@ public LDDB() ///
public string FilePath { - get => _filePath; // 获取文件路径 + get + { + return _filePath; // 获取文件路径 + } set { - ValidateFilePath(value); // 在设置值之前进行验证 - _filePath = value; // 只有通过验证后才设置值 + if (ValidateFilePath(value)) // 在设置值之前进行验证 + { + _filePath = value; + } } } /// @@ -57,12 +62,15 @@ public string FilePath /// /// 路径 /// - private static void ValidateFilePath(string path) + /// If true, it can be used, if false, it cannot be used.
如果为true则可以使用,若为false则不可使用。
+ private static bool ValidateFilePath(string path) { if (string.IsNullOrWhiteSpace(path)) { + return false; throw new FilePathIsNullOrWhiteSpace("文件路径不能为 null 或空白"); } + return true; } /// From c11689f19cc6770d5566dae1bab94d93d9b4fa36 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 30 Dec 2024 16:39:33 +0800 Subject: [PATCH 39/52] =?UTF-8?q?chore:=20=E5=88=A0=E9=99=A4=E4=B8=8D?= =?UTF-8?q?=E9=9C=80=E8=A6=81=E7=9A=84=E8=A7=A6=E5=8F=91=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/TYLDDB/TYLDDB.cs b/TYLDDB/TYLDDB.cs index ddca467..7dda56f 100644 --- a/TYLDDB/TYLDDB.cs +++ b/TYLDDB/TYLDDB.cs @@ -27,7 +27,6 @@ public LDDB() private string _database; // 存储正在访问的数据库 private string _databaseContent; // 存储数据库内容 private bool _isRead = false; // 是否已调用读取文件 - private event Action OnFileReadComplete; private Database database = new Database(); private Cache cdCache = new ConcurrentDictionary(); private Cache stlCache = new SemaphoreThreadLock(); From 47794712d52ac03b03df7e54da42e04cb7555dca Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 30 Dec 2024 16:51:51 +0800 Subject: [PATCH 40/52] =?UTF-8?q?style:=20=E4=BF=AE=E6=94=B9=E7=B1=BB?= =?UTF-8?q?=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/Parser/Parser.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TYLDDB/Parser/Parser.cs b/TYLDDB/Parser/Parser.cs index 326f561..02c995b 100644 --- a/TYLDDB/Parser/Parser.cs +++ b/TYLDDB/Parser/Parser.cs @@ -8,7 +8,7 @@ namespace TYLDDB.Parser /// Data type parser.
/// 数据类型解析器。 ///
- public class Parser + public class DataParser { // 定义正则表达式来匹配键值对(类型::"key"="value") private readonly static string pattern = @"(?<=^|\s)(\w+)\s*::\s*""([^""]+)"""; From 1cf749dcca1e008bc3762fddc22075226a7cd526 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 30 Dec 2024 17:32:54 +0800 Subject: [PATCH 41/52] =?UTF-8?q?feat:=20=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?=E7=BC=93=E5=AD=98=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 尝试了使用动态类型,但是很不幸,这会需要使用微软的一个包,原则上不使用第三方包,所有只能将字典重复写好多好多遍…… 要吐了…… 真不知道为什么要把动态拆开,就不能放进去吗…… --- TYLDDB.Test/Program.cs | 8 ++++++-- TYLDDB/TYLDDB.cs | 42 +++++++++++++++++++++++++++++++++++++----- TYLDDB/TYLDDB.csproj | 2 +- 3 files changed, 44 insertions(+), 8 deletions(-) diff --git a/TYLDDB.Test/Program.cs b/TYLDDB.Test/Program.cs index f727e38..9158a16 100644 --- a/TYLDDB.Test/Program.cs +++ b/TYLDDB.Test/Program.cs @@ -36,8 +36,12 @@ } WriteTime("从发起读取数据库名称到成功返回读取内容的总时间为: ", readAllDbNameTimer.ElapsedMilliseconds()); - - +///////////////////////////////////////////////////////////////////////////////////////////////////////// 数据库解析缓存 +HighPrecisionTimer parseDbTimer = new(); // 从发起解析文件到成功解析并写入缓存的总时间 +parseDbTimer.Start(); +await lddb.ParseAsync(); +parseDbTimer.Stop(); +WriteTime("从发起解析文件到成功解析并写入缓存的总时间: ", parseDbTimer.ElapsedMilliseconds()); diff --git a/TYLDDB/TYLDDB.cs b/TYLDDB/TYLDDB.cs index 7dda56f..4979989 100644 --- a/TYLDDB/TYLDDB.cs +++ b/TYLDDB/TYLDDB.cs @@ -1,6 +1,7 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; +using System.Threading.Tasks; using TYLDDB.Basic; +using TYLDDB.Parser; using TYLDDB.Utils; using TYLDDB.Utils.FastCache; @@ -28,8 +29,8 @@ public LDDB() private string _databaseContent; // 存储数据库内容 private bool _isRead = false; // 是否已调用读取文件 private Database database = new Database(); - private Cache cdCache = new ConcurrentDictionary(); - private Cache stlCache = new SemaphoreThreadLock(); + private ConcurrentDictionary cdStringCache = new ConcurrentDictionary(); + private SemaphoreThreadLock stlCache = new SemaphoreThreadLock(); ///////////////////////////////////////////////////// 公开字段 /// @@ -87,7 +88,7 @@ public void ReadingFile() /// 设置要加载的数据库 /// /// name of the database
数据库名称 - public void LoadDatabase(string db) + public async void LoadDatabase(string db) { switch (_isRead) { @@ -99,6 +100,7 @@ public void LoadDatabase(string db) _databaseContent = database.GetDatabaseContent(_fileContent, db); break; } + await ParseAsync(); } /// @@ -112,5 +114,35 @@ public void LoadDatabase(string db) /// 读取全部数据库的名称 /// public void ReadAllDatabaseName() => AllDatabaseName = database.GetDatabaseList(_fileContent); + + /// + /// Reparse the entire database.
+ /// 重新解析整个数据库。 + ///
+ public async Task ParseAsync() + { + // 创建多个任务,并使用 LongRunning 来确保每个任务在独立线程中运行 + Task cdStringCacheTask = Task.Factory.StartNew(() => CdString(), TaskCreationOptions.LongRunning); + //Task cdIntCacheTask = Task.Factory.StartNew(() => CdInt(), TaskCreationOptions.LongRunning); + //Task cdShortCacheTask = Task.Factory.StartNew(() => CdShort(), TaskCreationOptions.LongRunning); + + // 等待所有任务完成 + await Task.WhenAll(cdStringCacheTask); + + async void CdString() + { + var dict = DataParser.ParseString(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await cdStringCache.SetAsync(key, value); + } + } + } } } diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index a8a6ed5..b470d6c 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -4,7 +4,7 @@ netstandard2.1;net6.0;net8.0;net9.0 True TYLDDB.NET - 1.0.0-alpha.3 + 1.0.0-alpha.4 TYLDDB-Project LICENSE True From 23167eb501449873261c13366f3b8de772ac13d4 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 30 Dec 2024 17:41:25 +0800 Subject: [PATCH 42/52] delete test proj --- TYLDDB-CSharp.sln | 21 --- TYLDDB.Parser.Test/Program.cs | 33 ---- TYLDDB.Parser.Test/TYLDDB.Parser.Test.csproj | 15 -- TYLDDB.Utils.FastCache.Test/Program.cs | 149 ------------------ .../TYLDDB.Utils.FastCache.Test.csproj | 15 -- TYLDDB.Utils.Writer.Test/Program.cs | 37 ----- .../TYLDDB.Utils.Writer.Test.csproj | 15 -- TYLDDB/TYLDDB.csproj | 5 + 8 files changed, 5 insertions(+), 285 deletions(-) delete mode 100644 TYLDDB.Parser.Test/Program.cs delete mode 100644 TYLDDB.Parser.Test/TYLDDB.Parser.Test.csproj delete mode 100644 TYLDDB.Utils.FastCache.Test/Program.cs delete mode 100644 TYLDDB.Utils.FastCache.Test/TYLDDB.Utils.FastCache.Test.csproj delete mode 100644 TYLDDB.Utils.Writer.Test/Program.cs delete mode 100644 TYLDDB.Utils.Writer.Test/TYLDDB.Utils.Writer.Test.csproj diff --git a/TYLDDB-CSharp.sln b/TYLDDB-CSharp.sln index d409f8a..bd725a6 100644 --- a/TYLDDB-CSharp.sln +++ b/TYLDDB-CSharp.sln @@ -12,16 +12,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TYLDDB.Test", "TYLDDB.Test\TYLDDB.Test.csproj", "{FDFD566C-CB13-43EB-970E-0EC0A21E36C0}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TYLDDB.Utils.FastCache.Test", "TYLDDB.Utils.FastCache.Test\TYLDDB.Utils.FastCache.Test.csproj", "{A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TYLDDB.Utils.Writer.Test", "TYLDDB.Utils.Writer.Test\TYLDDB.Utils.Writer.Test.csproj", "{1BA4CC53-078F-4943-B8EF-A522DA9E5060}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TimeRecord", "TimeRecord\TimeRecord.csproj", "{F95CF6BC-2255-47F8-AAB3-B7812BB2894D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TYLDDB.Parser.Test", "TYLDDB.Parser.Test\TYLDDB.Parser.Test.csproj", "{0B96CCF3-16C7-4B18-9D07-A19D5D8E9641}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -36,32 +30,17 @@ Global {FDFD566C-CB13-43EB-970E-0EC0A21E36C0}.Debug|Any CPU.Build.0 = Debug|Any CPU {FDFD566C-CB13-43EB-970E-0EC0A21E36C0}.Release|Any CPU.ActiveCfg = Release|Any CPU {FDFD566C-CB13-43EB-970E-0EC0A21E36C0}.Release|Any CPU.Build.0 = Release|Any CPU - {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B}.Release|Any CPU.Build.0 = Release|Any CPU - {1BA4CC53-078F-4943-B8EF-A522DA9E5060}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1BA4CC53-078F-4943-B8EF-A522DA9E5060}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1BA4CC53-078F-4943-B8EF-A522DA9E5060}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1BA4CC53-078F-4943-B8EF-A522DA9E5060}.Release|Any CPU.Build.0 = Release|Any CPU {F95CF6BC-2255-47F8-AAB3-B7812BB2894D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F95CF6BC-2255-47F8-AAB3-B7812BB2894D}.Debug|Any CPU.Build.0 = Debug|Any CPU {F95CF6BC-2255-47F8-AAB3-B7812BB2894D}.Release|Any CPU.ActiveCfg = Release|Any CPU {F95CF6BC-2255-47F8-AAB3-B7812BB2894D}.Release|Any CPU.Build.0 = Release|Any CPU - {0B96CCF3-16C7-4B18-9D07-A19D5D8E9641}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0B96CCF3-16C7-4B18-9D07-A19D5D8E9641}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0B96CCF3-16C7-4B18-9D07-A19D5D8E9641}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0B96CCF3-16C7-4B18-9D07-A19D5D8E9641}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {FDFD566C-CB13-43EB-970E-0EC0A21E36C0} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} - {A58C0A6B-9BD4-4B29-9B5F-5FDFB849D23B} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} - {1BA4CC53-078F-4943-B8EF-A522DA9E5060} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} {F95CF6BC-2255-47F8-AAB3-B7812BB2894D} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} - {0B96CCF3-16C7-4B18-9D07-A19D5D8E9641} = {95BC8FAF-AB03-44A3-A7E7-8E42FA7138E3} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {19390089-354C-41AD-AF7D-9FB3998A88EA} diff --git a/TYLDDB.Parser.Test/Program.cs b/TYLDDB.Parser.Test/Program.cs deleted file mode 100644 index fc62551..0000000 --- a/TYLDDB.Parser.Test/Program.cs +++ /dev/null @@ -1,33 +0,0 @@ -using TimeRecord; -using TYLDDB.Parser; - -string content = @" -string::""str_name""=""name1""; -int::""int_value""=""123""; -short::""short_value""=""32767""; -long::""long_value""=""2147483647""; -float::""float_value""=""3.14f""; -double::""double_value""=""3.141592653589793""; -boolean::""bool""=""true""; -char::""char_value""=""127""; -decimal::decima_value = 19.99m""; -internaldb::""db_name""={}; -"; - -var parser = new Parser(); -var time = new HighPrecisionTimer(); -time.Start(); -// 调用 Parse 方法进行解析 -var result = Parser.ParseString(content); -time.Stop(); -// 输出找到的所有键值对 -if (result.Count > 0) -{ - foreach (var entry in result) - { - Console.WriteLine($"{entry.Key}: {entry.Value}"); - } -} - -Console.WriteLine($"Time: {time.ElapsedMilliseconds()}ms"); -Console.ReadLine(); \ No newline at end of file diff --git a/TYLDDB.Parser.Test/TYLDDB.Parser.Test.csproj b/TYLDDB.Parser.Test/TYLDDB.Parser.Test.csproj deleted file mode 100644 index 700866e..0000000 --- a/TYLDDB.Parser.Test/TYLDDB.Parser.Test.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - Exe - net8.0 - enable - enable - - - - - - - - diff --git a/TYLDDB.Utils.FastCache.Test/Program.cs b/TYLDDB.Utils.FastCache.Test/Program.cs deleted file mode 100644 index 5172226..0000000 --- a/TYLDDB.Utils.FastCache.Test/Program.cs +++ /dev/null @@ -1,149 +0,0 @@ -using TimeRecord; -using TYLDDB.Utils.FastCache; - -Console.WriteLine("基于信号量的缓存读写运行"); -SemaphoreSlimDefault(); - -Console.WriteLine(); -Console.WriteLine("基于信号量的缓存读写运行"); -ConcurrentDictionary(); -Console.ReadLine(); - -// 基于信号量的缓存读写运行 -static async void SemaphoreSlimDefault() -{ - var setTime = new HighPrecisionTimer(); - var setAsyncTime = new HighPrecisionTimer(); - var getByKeyTime = new HighPrecisionTimer(); - var getByKeyAsyncTime = new HighPrecisionTimer(); - var getKeysByValueTime = new HighPrecisionTimer(); - var getKeysByValueAsyncTime = new HighPrecisionTimer(); - var getAllCacheTime = new HighPrecisionTimer(); - var getAllCacheAsyncTime = new HighPrecisionTimer(); - - var cache = new SemaphoreThreadLock(); - - setTime.Start(); - cache.Set("TESTKEY1", "TESTVALUE1"); - setTime.Stop(); - - setAsyncTime.Start(); - await cache.SetAsync("TESTKEY2", "TESTVALUE2"); - setAsyncTime.Stop(); - - getByKeyTime.Start(); - Console.WriteLine("TESTKEY1对应的值:" + cache.GetByKey("TESTKEY1")); - getByKeyTime.Stop(); - - getByKeyAsyncTime.Start(); - Console.WriteLine("TESTKEY2对应的值:" + await cache.GetByKeyAsync("TESTKEY2")); - getByKeyAsyncTime.Stop(); - - cache.Set("TESTKEY3", "TESTVALUE2"); - - Console.WriteLine("TESTVALUE2对应的所有键:"); - getKeysByValueTime.Start(); - Console.WriteLine(string.Join(", ", cache.GetKeysByValue("TESTVALUE2"))); - getKeysByValueTime.Stop(); - - Console.WriteLine("TESTVALUE2对应的所有键:"); - getKeysByValueAsyncTime.Start(); - Console.WriteLine(string.Join(", ", await cache.GetKeysByValueAsync("TESTVALUE2"))); - getKeysByValueAsyncTime.Stop(); - - // 获取并输出所有缓存项(同步方法) - getAllCacheTime.Start(); - var allCacheSync = cache.GetAllCache(); - Console.WriteLine("同步获取所有缓存项:"); - foreach (var kvp in allCacheSync) - { - Console.WriteLine($"{kvp.Key}: {kvp.Value}"); - } - getAllCacheTime.Stop(); - - // 获取并输出所有缓存项(异步方法) - getAllCacheAsyncTime.Start(); - var allCacheAsync = await cache.GetAllCacheAsync(); - Console.WriteLine("异步获取所有缓存项:"); - foreach (var kvp in allCacheAsync) - { - Console.WriteLine($"{kvp.Key}: {kvp.Value}"); - } - getAllCacheAsyncTime.Stop(); - - - Console.WriteLine("时间消耗:"); - Console.WriteLine($"设置键值(同步):{setTime.ElapsedMilliseconds()}ms 设置键值(异步):{setAsyncTime.ElapsedMilliseconds()}ms"); - Console.WriteLine($"根据键获取值(同步):{getByKeyTime.ElapsedMilliseconds()}ms 根据键获取值(异步):{getByKeyAsyncTime.ElapsedMilliseconds()}ms"); - Console.WriteLine($"根据值获取键(同步):{getKeysByValueTime.ElapsedMilliseconds()}ms 根据值获取键(异步):{getKeysByValueAsyncTime.ElapsedMilliseconds()}ms"); - Console.WriteLine($"获取所有缓存项(同步):{getAllCacheTime.ElapsedMilliseconds()}ms 获取所有缓存项(异步):{getAllCacheAsyncTime.ElapsedMilliseconds()}ms"); -} - -// 基于并发词典的缓存读写运行 -static async void ConcurrentDictionary() -{ - var setTime = new HighPrecisionTimer(); - var setAsyncTime = new HighPrecisionTimer(); - var getByKeyTime = new HighPrecisionTimer(); - var getByKeyAsyncTime = new HighPrecisionTimer(); - var getKeysByValueTime = new HighPrecisionTimer(); - var getKeysByValueAsyncTime = new HighPrecisionTimer(); - var getAllCacheTime = new HighPrecisionTimer(); - var getAllCacheAsyncTime = new HighPrecisionTimer(); - - var cache = new ConcurrentDictionary(); - - setTime.Start(); - cache.Set("TESTKEY1", "TESTVALUE1"); - setTime.Stop(); - - setAsyncTime.Start(); - await cache.SetAsync("TESTKEY2", "TESTVALUE2"); - setAsyncTime.Stop(); - - getByKeyTime.Start(); - Console.WriteLine("TESTKEY1对应的值:" + cache.GetByKey("TESTKEY1")); - getByKeyTime.Stop(); - - getByKeyAsyncTime.Start(); - Console.WriteLine("TESTKEY2对应的值:" + await cache.GetByKeyAsync("TESTKEY2")); - getByKeyAsyncTime.Stop(); - - cache.Set("TESTKEY3", "TESTVALUE2"); - - Console.WriteLine("TESTVALUE2对应的所有键:"); - getKeysByValueTime.Start(); - Console.WriteLine(string.Join(", ", cache.GetKeysByValue("TESTVALUE2"))); - getKeysByValueTime.Stop(); - - Console.WriteLine("TESTVALUE2对应的所有键:"); - getKeysByValueAsyncTime.Start(); - Console.WriteLine(string.Join(", ", await cache.GetKeysByValueAsync("TESTVALUE2"))); - getKeysByValueAsyncTime.Stop(); - - // 获取并输出所有缓存项(同步方法) - getAllCacheTime.Start(); - var allCacheSync = cache.GetAllCache(); - Console.WriteLine("同步获取所有缓存项:"); - foreach (var kvp in allCacheSync) - { - Console.WriteLine($"{kvp.Key}: {kvp.Value}"); - } - getAllCacheTime.Stop(); - - // 获取并输出所有缓存项(异步方法) - getAllCacheAsyncTime.Start(); - var allCacheAsync = await cache.GetAllCacheAsync(); - Console.WriteLine("异步获取所有缓存项:"); - foreach (var kvp in allCacheAsync) - { - Console.WriteLine($"{kvp.Key}: {kvp.Value}"); - } - getAllCacheAsyncTime.Stop(); - - Console.WriteLine("时间消耗:"); - Console.WriteLine($"设置键值(同步):{setTime.ElapsedMilliseconds()}ms 设置键值(异步):{setAsyncTime.ElapsedMilliseconds()}ms"); - Console.WriteLine($"根据键获取值(同步):{getByKeyTime.ElapsedMilliseconds()}ms 根据键获取值(异步):{getByKeyAsyncTime.ElapsedMilliseconds()}ms"); - Console.WriteLine($"根据值获取键(同步):{getKeysByValueTime.ElapsedMilliseconds()}ms 根据值获取键(异步):{getKeysByValueAsyncTime.ElapsedMilliseconds()}ms"); - Console.WriteLine($"获取所有缓存项(同步):{getAllCacheTime.ElapsedMilliseconds()}ms 获取所有缓存项(异步):{getAllCacheAsyncTime.ElapsedMilliseconds()}ms"); -} diff --git a/TYLDDB.Utils.FastCache.Test/TYLDDB.Utils.FastCache.Test.csproj b/TYLDDB.Utils.FastCache.Test/TYLDDB.Utils.FastCache.Test.csproj deleted file mode 100644 index 700866e..0000000 --- a/TYLDDB.Utils.FastCache.Test/TYLDDB.Utils.FastCache.Test.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - Exe - net8.0 - enable - enable - - - - - - - - diff --git a/TYLDDB.Utils.Writer.Test/Program.cs b/TYLDDB.Utils.Writer.Test/Program.cs deleted file mode 100644 index 2e269e1..0000000 --- a/TYLDDB.Utils.Writer.Test/Program.cs +++ /dev/null @@ -1,37 +0,0 @@ -using TimeRecord; -using TYLDDB.Utils; - -string largeString = new('A', 1); -string syncFilePath = "sync.txt"; -string asyncFilePath = "async.txt"; -string syncChunkFilePath = "sync-chunk.txt"; -string asyncChunkFilePath = "async-chunk.txt"; - -var syncTime = new HighPrecisionTimer(); -var asyncTime = new HighPrecisionTimer(); -var syncChunkTime = new HighPrecisionTimer(); -var asyncChunkTime = new HighPrecisionTimer(); - -syncTime.Start(); -Writer.WriteStringToFile(syncFilePath, largeString); -syncTime.Stop(); - -asyncTime.Start(); -await Writer.WriteStringToFileAsync(asyncFilePath, largeString); -asyncTime.Stop(); - -syncChunkTime.Start(); -Writer.WriteStringToFileInChunks(syncChunkFilePath, largeString); -syncChunkTime.Stop(); - -asyncChunkTime.Start(); -await Writer.WriteStringToFileInChunksAsync(asyncChunkFilePath, largeString); -asyncChunkTime.Stop(); - -Console.WriteLine("测试结果:"); -Console.WriteLine($"同步写入:{syncTime.ElapsedMilliseconds()}ms"); -Console.WriteLine($"异步写入:{asyncTime.ElapsedMilliseconds()}ms"); -Console.WriteLine($"同步分块写入:{syncChunkTime.ElapsedMilliseconds()}ms"); -Console.WriteLine($"异步分块写入:{asyncChunkTime.ElapsedMilliseconds()}ms"); - -Console.ReadLine(); diff --git a/TYLDDB.Utils.Writer.Test/TYLDDB.Utils.Writer.Test.csproj b/TYLDDB.Utils.Writer.Test/TYLDDB.Utils.Writer.Test.csproj deleted file mode 100644 index 700866e..0000000 --- a/TYLDDB.Utils.Writer.Test/TYLDDB.Utils.Writer.Test.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - Exe - net8.0 - enable - enable - - - - - - - - diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index b470d6c..ad917c6 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -50,4 +50,9 @@ Fast cache underlying interface optimization. + + + + + From e66327d119812ecf8305716eb344ef45a0a28854 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 30 Dec 2024 17:47:43 +0800 Subject: [PATCH 43/52] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=E7=BC=93?= =?UTF-8?q?=E5=AD=98=E4=BB=A3=E7=A0=81=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.cs | 9 +++++---- TYLDDB/TYLDDB.csproj | 5 ----- .../CdStringDictionary.cs} | 4 ++-- .../StlStringDictionary.cs} | 6 +++--- 4 files changed, 10 insertions(+), 14 deletions(-) rename TYLDDB/Utils/FastCache/{ConcurrentDictionary.cs => ConcurrentDictionary/CdStringDictionary.cs} (97%) rename TYLDDB/Utils/FastCache/{SemaphoreThreadLock.cs => SemaphoreThreadLock/StlStringDictionary.cs} (98%) diff --git a/TYLDDB/TYLDDB.cs b/TYLDDB/TYLDDB.cs index 4979989..cdc8d6a 100644 --- a/TYLDDB/TYLDDB.cs +++ b/TYLDDB/TYLDDB.cs @@ -3,7 +3,8 @@ using TYLDDB.Basic; using TYLDDB.Parser; using TYLDDB.Utils; -using TYLDDB.Utils.FastCache; +using TYLDDB.Utils.FastCache.ConcurrentDictionary; +using TYLDDB.Utils.FastCache.SemaphoreThreadLock; namespace TYLDDB { @@ -29,8 +30,8 @@ public LDDB() private string _databaseContent; // 存储数据库内容 private bool _isRead = false; // 是否已调用读取文件 private Database database = new Database(); - private ConcurrentDictionary cdStringCache = new ConcurrentDictionary(); - private SemaphoreThreadLock stlCache = new SemaphoreThreadLock(); + private CdStringDictionary cdStringDictionary = new CdStringDictionary(); + private StlStringDictionary StlStringDictionary = new StlStringDictionary(); ///////////////////////////////////////////////////// 公开字段 /// @@ -140,7 +141,7 @@ async void CdString() var value = kvp.Value; // 获取第二个值 (value) // 将 key-value 对存储到缓存 - await cdStringCache.SetAsync(key, value); + await cdStringDictionary.SetAsync(key, value); } } } diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index ad917c6..b470d6c 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -50,9 +50,4 @@ Fast cache underlying interface optimization. - - - - - diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdStringDictionary.cs similarity index 97% rename from TYLDDB/Utils/FastCache/ConcurrentDictionary.cs rename to TYLDDB/Utils/FastCache/ConcurrentDictionary/CdStringDictionary.cs index ba98a93..9e85a18 100644 --- a/TYLDDB/Utils/FastCache/ConcurrentDictionary.cs +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdStringDictionary.cs @@ -1,13 +1,13 @@ using System.Collections.Concurrent; using System.Collections.Generic; -namespace TYLDDB.Utils.FastCache +namespace TYLDDB.Utils.FastCache.ConcurrentDictionary { /// /// Use thread locks based on concurrent dictionaries to achieve high concurrency stability.
/// 使用基于信号量的线程锁来实现高并发的稳定性。 ///
- public class ConcurrentDictionary : Cache + public class CdStringDictionary : Cache { /// /// Thread-safe dictionary to store cache data.
diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlStringDictionary.cs similarity index 98% rename from TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs rename to TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlStringDictionary.cs index c7ff0a5..37a650e 100644 --- a/TYLDDB/Utils/FastCache/SemaphoreThreadLock.cs +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlStringDictionary.cs @@ -3,13 +3,13 @@ using System.Threading; using System.Threading.Tasks; -namespace TYLDDB.Utils.FastCache +namespace TYLDDB.Utils.FastCache.SemaphoreThreadLock { /// /// Use semaphore based thread locks to achieve high concurrency stability.
/// 使用基于信号量的线程锁来实现高并发的稳定性。 ///
- public class SemaphoreThreadLock : Cache + public class StlStringDictionary : Cache { private readonly Dictionary keyValueDict; // 存储键->值映射 private readonly Dictionary> valueKeyDict; // 存储值->键的映射 @@ -19,7 +19,7 @@ public class SemaphoreThreadLock : Cache /// Use cached key-value pairs for fast reads and writes.
/// 使用缓存的键值对来快速读写。 ///
- public SemaphoreThreadLock() + public StlStringDictionary() { keyValueDict = new Dictionary(); valueKeyDict = new Dictionary>(); From e3147fdf74d53b01a7f0961b459182fd193c9892 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 30 Dec 2024 20:18:27 +0800 Subject: [PATCH 44/52] =?UTF-8?q?refactor:=20=E5=88=A0=E9=99=A4=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/Utils/FastCache/Cache.cs | 39 ------- .../CdStringDictionary.cs | 57 ++++++++-- TYLDDB/Utils/FastCache/ICache.cs | 104 ------------------ .../StlStringDictionary.cs | 26 ++--- 4 files changed, 60 insertions(+), 166 deletions(-) delete mode 100644 TYLDDB/Utils/FastCache/Cache.cs delete mode 100644 TYLDDB/Utils/FastCache/ICache.cs diff --git a/TYLDDB/Utils/FastCache/Cache.cs b/TYLDDB/Utils/FastCache/Cache.cs deleted file mode 100644 index dc06ba2..0000000 --- a/TYLDDB/Utils/FastCache/Cache.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; - -namespace TYLDDB.Utils.FastCache -{ - /// - /// For cached abstract classes, you need to inherit the class to do concrete implementation.
- /// 对于缓存的抽象类,需要继承该类来做具体实现。 - ///
- public abstract class Cache : ICache - { - /// - public abstract void Clear(); - /// - public virtual async Task ClearAsync() => await Task.Run(() => Clear()); - /// - public abstract Dictionary GetAllCache(); - /// - public virtual async Task> GetAllCacheAsync() => await Task.FromResult(GetAllCache()); - /// - public abstract string GetByKey(string key); - /// - public virtual async Task GetByKeyAsync(string key) => await Task.FromResult(GetByKey(key)); - /// - public abstract List GetKeysByValue(string value); - /// - public virtual async Task> GetKeysByValueAsync(string value) => await Task.FromResult(GetKeysByValue(value)); - /// - public abstract bool RemoveByKey(string key); - /// - public virtual async Task RemoveByKeyAsync(string key) => await Task.FromResult(RemoveByKey(key)); - /// - public abstract bool Set(string key, string value); - /// - public virtual async Task SetAsync(string key, string value) => await Task.FromResult(Set(key, value)); - } -} diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdStringDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdStringDictionary.cs index 9e85a18..c92e73d 100644 --- a/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdStringDictionary.cs +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdStringDictionary.cs @@ -1,5 +1,6 @@ using System.Collections.Concurrent; using System.Collections.Generic; +using System.Threading.Tasks; namespace TYLDDB.Utils.FastCache.ConcurrentDictionary { @@ -7,7 +8,7 @@ namespace TYLDDB.Utils.FastCache.ConcurrentDictionary /// Use thread locks based on concurrent dictionaries to achieve high concurrency stability.
/// 使用基于信号量的线程锁来实现高并发的稳定性。 ///
- public class CdStringDictionary : Cache + public class CdStringDictionary { /// /// Thread-safe dictionary to store cache data.
@@ -21,19 +22,27 @@ public class CdStringDictionary : Cache ///
/// Key
键 /// Value
- public override string GetByKey(string key) + public virtual string GetByKey(string key) { _cache.TryGetValue(key, out var value); return value; } + /// + /// Asynchronous method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) => await Task.FromResult(GetByKey(key)); + /// /// Get a list of keys that correspond to a specific value.
/// 获取与指定值对应的所有键的列表。 ///
/// Value to match
要匹配的值 /// List of keys
键的列表
- public override List GetKeysByValue(string value) + public virtual List GetKeysByValue(string value) { var keys = new List(); foreach (var kvp in _cache) @@ -46,6 +55,14 @@ public override List GetKeysByValue(string value) return keys; } + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual async Task> GetKeysByValueAsync(string value) => await Task.FromResult(GetKeysByValue(value)); + /// /// Set a cache entry for a specified key.
/// 为指定键设置缓存项。 @@ -53,35 +70,55 @@ public override List GetKeysByValue(string value) /// Key
键 /// Value
值 /// Whether the operation is successful.
操作是否成功。
- public override bool Set(string key, string value) + public virtual bool Set(string key, string value) { // Using AddOrUpdate to ensure atomic insert or update operation _cache.AddOrUpdate(key, value, (existingKey, existingValue) => value); return true; } + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual async Task SetAsync(string key, string value) => await Task.FromResult(Set(key, value)); + /// /// Remove a cache entry by its key.
/// 根据键移除缓存项。 ///
/// Key
键 /// Whether the removal is successful.
移除操作是否成功。
- public override bool RemoveByKey(string key) - { - return _cache.TryRemove(key, out _); - } + public virtual bool RemoveByKey(string key) => _cache.TryRemove(key, out _); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual async Task RemoveByKeyAsync(string key) => await Task.FromResult(RemoveByKey(key)); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual void Clear() => _cache.Clear(); /// /// Clear all cache entries.
/// 清空所有缓存项。 ///
- public override void Clear() => _cache.Clear(); + public virtual async Task ClearAsync() => await Task.Run(() => Clear()); /// /// Get all cache entries as a dictionary.
/// 获取所有缓存项,返回字典。 ///
/// All cache entries as a dictionary.
所有缓存项的字典。
- public override Dictionary GetAllCache() => new Dictionary(_cache); + public virtual Dictionary GetAllCache() => new Dictionary(_cache); } } diff --git a/TYLDDB/Utils/FastCache/ICache.cs b/TYLDDB/Utils/FastCache/ICache.cs deleted file mode 100644 index ea3ecce..0000000 --- a/TYLDDB/Utils/FastCache/ICache.cs +++ /dev/null @@ -1,104 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace TYLDDB.Utils.FastCache -{ - /// - /// Use cached key-value pairs for fast reads and writes.
- /// 使用缓存的键值对来快速读写。 - ///
- public interface ICache - { - /// - /// Synchronization method: Obtain the corresponding value by key.
- /// 同步方法:根据键获取对应的值。 - ///
- /// Key
键 - /// Value
- string GetByKey(string key); - - /// - /// Asynchronous method: Obtains the corresponding value based on the key.
- /// 异步方法:根据键获取对应的值。 - ///
- /// Key
键 - /// Value
- Task GetByKeyAsync(string key); - - /// - /// Synchronization method: Obtains one or more keys according to the value.
- /// 同步方法:根据值获取对应的一个或多个键。 - ///
- /// Value
值 - /// Key (List)
键 (List)
- List GetKeysByValue(string value); - - /// - /// Asynchronous method: Get one or more keys based on the value.
- /// 异步方法:根据值获取对应的一个或多个键。 - ///
- /// Value
值 - /// Key (List)
键 (List)
- Task> GetKeysByValueAsync(string value); - - /// - /// Set a key-value pair.
- /// 设置一个键值对。 - ///
- /// Key
键 - /// Value
值 - /// Whether the Settings are successful.
是否设置成功。
- bool Set(string key, string value); - - /// - /// Set a key-value pair.
- /// 设置一个键值对。 - ///
- /// Key
键 - /// Value
值 - /// Whether the Settings are successful.
是否设置成功。
- Task SetAsync(string key, string value); - - /// - /// Remove a key-value pair.
- /// 移除一个键值对。 - ///
- /// Key
键 - /// Whether the removal was successful or not.
是否移除成功。
- bool RemoveByKey(string key); - - /// - /// Remove a key-value pair.
- /// 移除一个键值对。 - ///
- /// Key
键 - /// Whether the removal was successful or not.
是否移除成功。
- Task RemoveByKeyAsync(string key); - - /// - /// Clear the cache.
- /// 清空缓存。 - ///
- void Clear(); - - /// - /// Clear the cache.
- /// 清空缓存。 - ///
- Task ClearAsync(); - - /// - /// Gets all key-value pairs.
- /// 获取所有的键值对。 - ///
- /// Key-value pair
键值对
- Dictionary GetAllCache(); - - /// - /// Gets all key-value pairs.
- /// 获取所有的键值对。 - ///
- /// Key-value pair
键值对
- Task> GetAllCacheAsync(); - } -} diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlStringDictionary.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlStringDictionary.cs index 37a650e..9232866 100644 --- a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlStringDictionary.cs +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlStringDictionary.cs @@ -9,7 +9,7 @@ namespace TYLDDB.Utils.FastCache.SemaphoreThreadLock /// Use semaphore based thread locks to achieve high concurrency stability.
/// 使用基于信号量的线程锁来实现高并发的稳定性。 ///
- public class StlStringDictionary : Cache + public class StlStringDictionary { private readonly Dictionary keyValueDict; // 存储键->值映射 private readonly Dictionary> valueKeyDict; // 存储值->键的映射 @@ -32,7 +32,7 @@ public StlStringDictionary() ///
/// Key
键 /// Value
- public override string GetByKey(string key) + public virtual string GetByKey(string key) { lock (semaphore) { @@ -47,7 +47,7 @@ public override string GetByKey(string key) /// /// Key
键 /// Value
- public override async Task GetByKeyAsync(string key) + public virtual async Task GetByKeyAsync(string key) { await semaphore.WaitAsync(); try @@ -67,7 +67,7 @@ public override async Task GetByKeyAsync(string key) /// /// Value
值 /// Key (List)
键 (List)
- public override List GetKeysByValue(string value) + public virtual List GetKeysByValue(string value) { lock (semaphore) { @@ -85,7 +85,7 @@ public override List GetKeysByValue(string value) /// /// Value
值 /// Key (List)
键 (List)
- public override async Task> GetKeysByValueAsync(string value) + public virtual async Task> GetKeysByValueAsync(string value) { await semaphore.WaitAsync(); try @@ -109,7 +109,7 @@ public override async Task> GetKeysByValueAsync(string value) /// Key
键 /// Value
值 /// Whether the Settings are successful.
是否设置成功
- public override bool Set(string key, string value) + public virtual bool Set(string key, string value) { lock (semaphore) { @@ -136,7 +136,7 @@ public override bool Set(string key, string value) /// Key
键 /// Value
值 /// Whether the Settings are successful.
是否设置成功
- public override async Task SetAsync(string key, string value) + public virtual async Task SetAsync(string key, string value) { await semaphore.WaitAsync(); try @@ -166,7 +166,7 @@ public override async Task SetAsync(string key, string value) /// /// /// - public override bool RemoveByKey(string key) + public virtual bool RemoveByKey(string key) { lock (semaphore) { @@ -194,7 +194,7 @@ public override bool RemoveByKey(string key) /// /// /// - public override async Task RemoveByKeyAsync(string key) + public virtual async Task RemoveByKeyAsync(string key) { await semaphore.WaitAsync(); try @@ -225,7 +225,7 @@ public override async Task RemoveByKeyAsync(string key) /// /// 同步方法:清空缓存。 /// - public override void Clear() + public virtual void Clear() { lock (semaphore) { @@ -238,7 +238,7 @@ public override void Clear() /// 异步方法:清空缓存。 /// /// - public override async Task ClearAsync() + public virtual async Task ClearAsync() { await semaphore.WaitAsync(); try @@ -257,7 +257,7 @@ public override async Task ClearAsync() /// 获取所有的键值对。 /// /// Key-value pair
键值对
- public override Dictionary GetAllCache() + public virtual Dictionary GetAllCache() { lock (semaphore) { @@ -271,7 +271,7 @@ public override Dictionary GetAllCache() /// 获取所有的键值对。 /// /// Key-value pair
键值对
- public override async Task> GetAllCacheAsync() + public virtual async Task> GetAllCacheAsync() { await semaphore.WaitAsync(); try From 81ae0b654ecbdc64b112c3470a0cd33324769c15 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 30 Dec 2024 20:18:41 +0800 Subject: [PATCH 45/52] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0int=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../StlIntegerDictionary.cs | 288 ++++++++++++++++++ 1 file changed, 288 insertions(+) create mode 100644 TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlIntegerDictionary.cs diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlIntegerDictionary.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlIntegerDictionary.cs new file mode 100644 index 0000000..e44d0c9 --- /dev/null +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlIntegerDictionary.cs @@ -0,0 +1,288 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.SemaphoreThreadLock +{ + /// + /// Use semaphore based thread locks to achieve high concurrency stability.
+ /// 使用基于信号量的线程锁来实现高并发的稳定性。 + ///
+ public class StlIntegerDictionary + { + private readonly Dictionary keyValueDict; // 存储键->值映射 + private readonly Dictionary> valueKeyDict; // 存储值->键的映射 + private readonly SemaphoreSlim semaphore; // 控制并发访问 + + /// + /// Use cached key-value pairs for fast reads and writes.
+ /// 使用缓存的键值对来快速读写。 + ///
+ public StlIntegerDictionary() + { + keyValueDict = new Dictionary(); + valueKeyDict = new Dictionary>(); + semaphore = new SemaphoreSlim(1, 1); // 使用信号量来同步 + } + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual int GetByKey(string key) + { + lock (semaphore) + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + } + + /// + /// Asynchronous method: Obtains the corresponding value based on the key.
+ /// 异步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Synchronization method: Obtains one or more keys according to the value.
+ /// 同步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual List GetKeysByValue(int value) + { + lock (semaphore) + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + } + + /// + /// Asynchronous method: Get one or more keys based on the value.
+ /// 异步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual async Task> GetKeysByValueAsync(int value) + { + await semaphore.WaitAsync(); + try + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual bool Set(string key, int value) + { + lock (semaphore) + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual async Task SetAsync(string key, int value) + { + await semaphore.WaitAsync(); + try + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// 同步方法:移除一个键值对。 + /// + /// + /// + public virtual bool RemoveByKey(string key) + { + lock (semaphore) + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + } + + /// + /// 异步方法:移除一个键值对。 + /// + /// + /// + public virtual async Task RemoveByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// 同步方法:清空缓存。 + /// + public virtual void Clear() + { + lock (semaphore) + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + } + + /// + /// 异步方法:清空缓存。 + /// + /// + public virtual async Task ClearAsync() + { + await semaphore.WaitAsync(); + try + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual Dictionary GetAllCache() + { + lock (semaphore) + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual async Task> GetAllCacheAsync() + { + await semaphore.WaitAsync(); + try + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + finally + { + semaphore.Release(); + } + } + } +} From c539e61e0cf6e39a11f2f7a31e92e8bb0cfe030b Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 30 Dec 2024 20:25:34 +0800 Subject: [PATCH 46/52] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0long=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../StlIntegerDictionary.cs | 23 +- .../SemaphoreThreadLock/StlLongDictionary.cs | 291 ++++++++++++++++++ .../StlStringDictionary.cs | 23 +- 3 files changed, 317 insertions(+), 20 deletions(-) create mode 100644 TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlLongDictionary.cs diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlIntegerDictionary.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlIntegerDictionary.cs index e44d0c9..b2e458d 100644 --- a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlIntegerDictionary.cs +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlIntegerDictionary.cs @@ -162,10 +162,11 @@ public virtual async Task SetAsync(string key, int value) } /// - /// 同步方法:移除一个键值对。 + /// Remove a key-value pair.
+ /// 移除一个键值对。 ///
- /// - /// + /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
public virtual bool RemoveByKey(string key) { lock (semaphore) @@ -190,10 +191,11 @@ public virtual bool RemoveByKey(string key) } /// - /// 异步方法:移除一个键值对。 + /// Remove a key-value pair.
+ /// 移除一个键值对。 ///
- /// - /// + /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
public virtual async Task RemoveByKeyAsync(string key) { await semaphore.WaitAsync(); @@ -223,7 +225,8 @@ public virtual async Task RemoveByKeyAsync(string key) } /// - /// 同步方法:清空缓存。 + /// Empty the cache.
+ /// 清空缓存。 ///
public virtual void Clear() { @@ -235,10 +238,10 @@ public virtual void Clear() } /// - /// 异步方法:清空缓存。 + /// Empty the cache.
+ /// 清空缓存。 ///
- /// - public virtual async Task ClearAsync() + public virtual async void ClearAsync() { await semaphore.WaitAsync(); try diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlLongDictionary.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlLongDictionary.cs new file mode 100644 index 0000000..91e7572 --- /dev/null +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlLongDictionary.cs @@ -0,0 +1,291 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.SemaphoreThreadLock +{ + /// + /// Use semaphore based thread locks to achieve high concurrency stability.
+ /// 使用基于信号量的线程锁来实现高并发的稳定性。 + ///
+ public class StlLongDictionary + { + private readonly Dictionary keyValueDict; // 存储键->值映射 + private readonly Dictionary> valueKeyDict; // 存储值->键的映射 + private readonly SemaphoreSlim semaphore; // 控制并发访问 + + /// + /// Use cached key-value pairs for fast reads and writes.
+ /// 使用缓存的键值对来快速读写。 + ///
+ public StlLongDictionary() + { + keyValueDict = new Dictionary(); + valueKeyDict = new Dictionary>(); + semaphore = new SemaphoreSlim(1, 1); // 使用信号量来同步 + } + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual long GetByKey(string key) + { + lock (semaphore) + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + } + + /// + /// Asynchronous method: Obtains the corresponding value based on the key.
+ /// 异步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Synchronization method: Obtains one or more keys according to the value.
+ /// 同步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual List GetKeysByValue(long value) + { + lock (semaphore) + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + } + + /// + /// Asynchronous method: Get one or more keys based on the value.
+ /// 异步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual async Task> GetKeysByValueAsync(long value) + { + await semaphore.WaitAsync(); + try + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual bool Set(string key, long value) + { + lock (semaphore) + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual async Task SetAsync(string key, long value) + { + await semaphore.WaitAsync(); + try + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual bool RemoveByKey(string key) + { + lock (semaphore) + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual async Task RemoveByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual void Clear() + { + lock (semaphore) + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual async void ClearAsync() + { + await semaphore.WaitAsync(); + try + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual Dictionary GetAllCache() + { + lock (semaphore) + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual async Task> GetAllCacheAsync() + { + await semaphore.WaitAsync(); + try + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + finally + { + semaphore.Release(); + } + } + } +} diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlStringDictionary.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlStringDictionary.cs index 9232866..09bc308 100644 --- a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlStringDictionary.cs +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlStringDictionary.cs @@ -162,10 +162,11 @@ public virtual async Task SetAsync(string key, string value) } /// - /// 同步方法:移除一个键值对。 + /// Remove a key-value pair.
+ /// 移除一个键值对。 ///
- /// - /// + /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
public virtual bool RemoveByKey(string key) { lock (semaphore) @@ -190,10 +191,11 @@ public virtual bool RemoveByKey(string key) } /// - /// 异步方法:移除一个键值对。 + /// Remove a key-value pair.
+ /// 移除一个键值对。 ///
- /// - /// + /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
public virtual async Task RemoveByKeyAsync(string key) { await semaphore.WaitAsync(); @@ -223,7 +225,8 @@ public virtual async Task RemoveByKeyAsync(string key) } /// - /// 同步方法:清空缓存。 + /// Empty the cache.
+ /// 清空缓存。 ///
public virtual void Clear() { @@ -235,10 +238,10 @@ public virtual void Clear() } /// - /// 异步方法:清空缓存。 + /// Empty the cache.
+ /// 清空缓存。 ///
- /// - public virtual async Task ClearAsync() + public virtual async void ClearAsync() { await semaphore.WaitAsync(); try From 4b159124afc023d12b2ce5594a0b70fea806bfb5 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 30 Dec 2024 20:33:20 +0800 Subject: [PATCH 47/52] =?UTF-8?q?feat:=20=E4=BF=A1=E5=8F=B7=E7=BA=BF?= =?UTF-8?q?=E7=A8=8B=E9=94=81=E7=BC=93=E5=AD=98=E5=85=A8=E9=83=A8=E5=AE=8C?= =?UTF-8?q?=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../StlBooleanDictionary.cs | 291 ++++++++++++++++++ .../SemaphoreThreadLock/StlCharDictionary.cs | 291 ++++++++++++++++++ .../StlDecimalDictionary.cs | 291 ++++++++++++++++++ .../StlDoubleDictionary.cs | 291 ++++++++++++++++++ .../SemaphoreThreadLock/StlFloatDictionary.cs | 291 ++++++++++++++++++ .../SemaphoreThreadLock/StlShortDictionary.cs | 291 ++++++++++++++++++ 6 files changed, 1746 insertions(+) create mode 100644 TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlBooleanDictionary.cs create mode 100644 TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlCharDictionary.cs create mode 100644 TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlDecimalDictionary.cs create mode 100644 TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlDoubleDictionary.cs create mode 100644 TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlFloatDictionary.cs create mode 100644 TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlShortDictionary.cs diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlBooleanDictionary.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlBooleanDictionary.cs new file mode 100644 index 0000000..6e41075 --- /dev/null +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlBooleanDictionary.cs @@ -0,0 +1,291 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.SemaphoreThreadLock +{ + /// + /// Use semaphore based thread locks to achieve high concurrency stability.
+ /// 使用基于信号量的线程锁来实现高并发的稳定性。 + ///
+ public class StlBooleanDictionary + { + private readonly Dictionary keyValueDict; // 存储键->值映射 + private readonly Dictionary> valueKeyDict; // 存储值->键的映射 + private readonly SemaphoreSlim semaphore; // 控制并发访问 + + /// + /// Use cached key-value pairs for fast reads and writes.
+ /// 使用缓存的键值对来快速读写。 + ///
+ public StlBooleanDictionary() + { + keyValueDict = new Dictionary(); + valueKeyDict = new Dictionary>(); + semaphore = new SemaphoreSlim(1, 1); // 使用信号量来同步 + } + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual bool GetByKey(string key) + { + lock (semaphore) + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + } + + /// + /// Asynchronous method: Obtains the corresponding value based on the key.
+ /// 异步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Synchronization method: Obtains one or more keys according to the value.
+ /// 同步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual List GetKeysByValue(bool value) + { + lock (semaphore) + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + } + + /// + /// Asynchronous method: Get one or more keys based on the value.
+ /// 异步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual async Task> GetKeysByValueAsync(bool value) + { + await semaphore.WaitAsync(); + try + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual bool Set(string key, bool value) + { + lock (semaphore) + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual async Task SetAsync(string key, bool value) + { + await semaphore.WaitAsync(); + try + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual bool RemoveByKey(string key) + { + lock (semaphore) + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual async Task RemoveByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual void Clear() + { + lock (semaphore) + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual async void ClearAsync() + { + await semaphore.WaitAsync(); + try + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual Dictionary GetAllCache() + { + lock (semaphore) + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual async Task> GetAllCacheAsync() + { + await semaphore.WaitAsync(); + try + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + finally + { + semaphore.Release(); + } + } + } +} diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlCharDictionary.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlCharDictionary.cs new file mode 100644 index 0000000..c2695e1 --- /dev/null +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlCharDictionary.cs @@ -0,0 +1,291 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.SemaphoreThreadLock +{ + /// + /// Use semaphore based thread locks to achieve high concurrency stability.
+ /// 使用基于信号量的线程锁来实现高并发的稳定性。 + ///
+ public class StlCharDictionary + { + private readonly Dictionary keyValueDict; // 存储键->值映射 + private readonly Dictionary> valueKeyDict; // 存储值->键的映射 + private readonly SemaphoreSlim semaphore; // 控制并发访问 + + /// + /// Use cached key-value pairs for fast reads and writes.
+ /// 使用缓存的键值对来快速读写。 + ///
+ public StlCharDictionary() + { + keyValueDict = new Dictionary(); + valueKeyDict = new Dictionary>(); + semaphore = new SemaphoreSlim(1, 1); // 使用信号量来同步 + } + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual char GetByKey(string key) + { + lock (semaphore) + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + } + + /// + /// Asynchronous method: Obtains the corresponding value based on the key.
+ /// 异步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Synchronization method: Obtains one or more keys according to the value.
+ /// 同步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual List GetKeysByValue(char value) + { + lock (semaphore) + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + } + + /// + /// Asynchronous method: Get one or more keys based on the value.
+ /// 异步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual async Task> GetKeysByValueAsync(char value) + { + await semaphore.WaitAsync(); + try + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual bool Set(string key, char value) + { + lock (semaphore) + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual async Task SetAsync(string key, char value) + { + await semaphore.WaitAsync(); + try + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual bool RemoveByKey(string key) + { + lock (semaphore) + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual async Task RemoveByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual void Clear() + { + lock (semaphore) + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual async void ClearAsync() + { + await semaphore.WaitAsync(); + try + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual Dictionary GetAllCache() + { + lock (semaphore) + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual async Task> GetAllCacheAsync() + { + await semaphore.WaitAsync(); + try + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + finally + { + semaphore.Release(); + } + } + } +} diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlDecimalDictionary.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlDecimalDictionary.cs new file mode 100644 index 0000000..ebd14bd --- /dev/null +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlDecimalDictionary.cs @@ -0,0 +1,291 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.SemaphoreThreadLock +{ + /// + /// Use semaphore based thread locks to achieve high concurrency stability.
+ /// 使用基于信号量的线程锁来实现高并发的稳定性。 + ///
+ public class StlDecimalDictionary + { + private readonly Dictionary keyValueDict; // 存储键->值映射 + private readonly Dictionary> valueKeyDict; // 存储值->键的映射 + private readonly SemaphoreSlim semaphore; // 控制并发访问 + + /// + /// Use cached key-value pairs for fast reads and writes.
+ /// 使用缓存的键值对来快速读写。 + ///
+ public StlDecimalDictionary() + { + keyValueDict = new Dictionary(); + valueKeyDict = new Dictionary>(); + semaphore = new SemaphoreSlim(1, 1); // 使用信号量来同步 + } + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual decimal GetByKey(string key) + { + lock (semaphore) + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + } + + /// + /// Asynchronous method: Obtains the corresponding value based on the key.
+ /// 异步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Synchronization method: Obtains one or more keys according to the value.
+ /// 同步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual List GetKeysByValue(decimal value) + { + lock (semaphore) + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + } + + /// + /// Asynchronous method: Get one or more keys based on the value.
+ /// 异步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual async Task> GetKeysByValueAsync(decimal value) + { + await semaphore.WaitAsync(); + try + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual bool Set(string key, decimal value) + { + lock (semaphore) + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual async Task SetAsync(string key, decimal value) + { + await semaphore.WaitAsync(); + try + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual bool RemoveByKey(string key) + { + lock (semaphore) + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual async Task RemoveByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual void Clear() + { + lock (semaphore) + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual async void ClearAsync() + { + await semaphore.WaitAsync(); + try + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual Dictionary GetAllCache() + { + lock (semaphore) + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual async Task> GetAllCacheAsync() + { + await semaphore.WaitAsync(); + try + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + finally + { + semaphore.Release(); + } + } + } +} diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlDoubleDictionary.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlDoubleDictionary.cs new file mode 100644 index 0000000..a2b624d --- /dev/null +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlDoubleDictionary.cs @@ -0,0 +1,291 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.SemaphoreThreadLock +{ + /// + /// Use semaphore based thread locks to achieve high concurrency stability.
+ /// 使用基于信号量的线程锁来实现高并发的稳定性。 + ///
+ public class StlDoubleDictionary + { + private readonly Dictionary keyValueDict; // 存储键->值映射 + private readonly Dictionary> valueKeyDict; // 存储值->键的映射 + private readonly SemaphoreSlim semaphore; // 控制并发访问 + + /// + /// Use cached key-value pairs for fast reads and writes.
+ /// 使用缓存的键值对来快速读写。 + ///
+ public StlDoubleDictionary() + { + keyValueDict = new Dictionary(); + valueKeyDict = new Dictionary>(); + semaphore = new SemaphoreSlim(1, 1); // 使用信号量来同步 + } + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual double GetByKey(string key) + { + lock (semaphore) + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + } + + /// + /// Asynchronous method: Obtains the corresponding value based on the key.
+ /// 异步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Synchronization method: Obtains one or more keys according to the value.
+ /// 同步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual List GetKeysByValue(double value) + { + lock (semaphore) + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + } + + /// + /// Asynchronous method: Get one or more keys based on the value.
+ /// 异步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual async Task> GetKeysByValueAsync(double value) + { + await semaphore.WaitAsync(); + try + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual bool Set(string key, double value) + { + lock (semaphore) + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual async Task SetAsync(string key, double value) + { + await semaphore.WaitAsync(); + try + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual bool RemoveByKey(string key) + { + lock (semaphore) + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual async Task RemoveByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual void Clear() + { + lock (semaphore) + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual async void ClearAsync() + { + await semaphore.WaitAsync(); + try + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual Dictionary GetAllCache() + { + lock (semaphore) + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual async Task> GetAllCacheAsync() + { + await semaphore.WaitAsync(); + try + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + finally + { + semaphore.Release(); + } + } + } +} diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlFloatDictionary.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlFloatDictionary.cs new file mode 100644 index 0000000..e746d61 --- /dev/null +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlFloatDictionary.cs @@ -0,0 +1,291 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.SemaphoreThreadLock +{ + /// + /// Use semaphore based thread locks to achieve high concurrency stability.
+ /// 使用基于信号量的线程锁来实现高并发的稳定性。 + ///
+ public class StlFloatDictionary + { + private readonly Dictionary keyValueDict; // 存储键->值映射 + private readonly Dictionary> valueKeyDict; // 存储值->键的映射 + private readonly SemaphoreSlim semaphore; // 控制并发访问 + + /// + /// Use cached key-value pairs for fast reads and writes.
+ /// 使用缓存的键值对来快速读写。 + ///
+ public StlFloatDictionary() + { + keyValueDict = new Dictionary(); + valueKeyDict = new Dictionary>(); + semaphore = new SemaphoreSlim(1, 1); // 使用信号量来同步 + } + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual float GetByKey(string key) + { + lock (semaphore) + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + } + + /// + /// Asynchronous method: Obtains the corresponding value based on the key.
+ /// 异步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Synchronization method: Obtains one or more keys according to the value.
+ /// 同步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual List GetKeysByValue(float value) + { + lock (semaphore) + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + } + + /// + /// Asynchronous method: Get one or more keys based on the value.
+ /// 异步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual async Task> GetKeysByValueAsync(float value) + { + await semaphore.WaitAsync(); + try + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual bool Set(string key, float value) + { + lock (semaphore) + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual async Task SetAsync(string key, float value) + { + await semaphore.WaitAsync(); + try + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual bool RemoveByKey(string key) + { + lock (semaphore) + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual async Task RemoveByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual void Clear() + { + lock (semaphore) + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual async void ClearAsync() + { + await semaphore.WaitAsync(); + try + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual Dictionary GetAllCache() + { + lock (semaphore) + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual async Task> GetAllCacheAsync() + { + await semaphore.WaitAsync(); + try + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + finally + { + semaphore.Release(); + } + } + } +} diff --git a/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlShortDictionary.cs b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlShortDictionary.cs new file mode 100644 index 0000000..0e74faf --- /dev/null +++ b/TYLDDB/Utils/FastCache/SemaphoreThreadLock/StlShortDictionary.cs @@ -0,0 +1,291 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.SemaphoreThreadLock +{ + /// + /// Use semaphore based thread locks to achieve high concurrency stability.
+ /// 使用基于信号量的线程锁来实现高并发的稳定性。 + ///
+ public class StlShortDictionary + { + private readonly Dictionary keyValueDict; // 存储键->值映射 + private readonly Dictionary> valueKeyDict; // 存储值->键的映射 + private readonly SemaphoreSlim semaphore; // 控制并发访问 + + /// + /// Use cached key-value pairs for fast reads and writes.
+ /// 使用缓存的键值对来快速读写。 + ///
+ public StlShortDictionary() + { + keyValueDict = new Dictionary(); + valueKeyDict = new Dictionary>(); + semaphore = new SemaphoreSlim(1, 1); // 使用信号量来同步 + } + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual short GetByKey(string key) + { + lock (semaphore) + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + } + + /// + /// Asynchronous method: Obtains the corresponding value based on the key.
+ /// 异步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + keyValueDict.TryGetValue(key, out var value); + return value; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Synchronization method: Obtains one or more keys according to the value.
+ /// 同步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual List GetKeysByValue(short value) + { + lock (semaphore) + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + } + + /// + /// Asynchronous method: Get one or more keys based on the value.
+ /// 异步方法:根据值获取对应的一个或多个键。 + ///
+ /// Value
值 + /// Key (List)
键 (List)
+ public virtual async Task> GetKeysByValueAsync(short value) + { + await semaphore.WaitAsync(); + try + { + if (valueKeyDict.ContainsKey(value)) + { + return valueKeyDict[value].ToList(); + } + return new List(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual bool Set(string key, short value) + { + lock (semaphore) + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + } + + /// + /// Set a key-value pair.
+ /// 设置一个键值对。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the Settings are successful.
是否设置成功
+ public virtual async Task SetAsync(string key, short value) + { + await semaphore.WaitAsync(); + try + { + if (keyValueDict.ContainsKey(key)) + { + return false; // 键已存在,不允许重复的键 + } + + keyValueDict[key] = value; + + if (!valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value] = new HashSet(); + } + valueKeyDict[value].Add(key); + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual bool RemoveByKey(string key) + { + lock (semaphore) + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + } + + /// + /// Remove a key-value pair.
+ /// 移除一个键值对。 + ///
+ /// Key
键 + /// Check whether the removal is successful.
是否移除成功。
+ public virtual async Task RemoveByKeyAsync(string key) + { + await semaphore.WaitAsync(); + try + { + if (!keyValueDict.ContainsKey(key)) + { + return false; + } + var value = keyValueDict[key]; + keyValueDict.Remove(key); + + if (valueKeyDict.ContainsKey(value)) + { + valueKeyDict[value].Remove(key); + if (valueKeyDict[value].Count == 0) + { + valueKeyDict.Remove(value); + } + } + return true; + } + finally + { + semaphore.Release(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual void Clear() + { + lock (semaphore) + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + } + + /// + /// Empty the cache.
+ /// 清空缓存。 + ///
+ public virtual async void ClearAsync() + { + await semaphore.WaitAsync(); + try + { + keyValueDict.Clear(); + valueKeyDict.Clear(); + } + finally + { + semaphore.Release(); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual Dictionary GetAllCache() + { + lock (semaphore) + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + } + + /// + /// Gets all key-value pairs.
+ /// 获取所有的键值对。 + ///
+ /// Key-value pair
键值对
+ public virtual async Task> GetAllCacheAsync() + { + await semaphore.WaitAsync(); + try + { + // 返回完整的键值对字典 + return new Dictionary(keyValueDict); + } + finally + { + semaphore.Release(); + } + } + } +} From 541b5be88c6299c959c2cab48be3c52d18fe8d76 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 30 Dec 2024 20:44:17 +0800 Subject: [PATCH 48/52] =?UTF-8?q?feat:=20=E5=B9=B6=E5=8F=91=E8=AF=8D?= =?UTF-8?q?=E5=85=B8=E7=BC=93=E5=AD=98=E5=85=A8=E9=83=A8=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CdBooleanDictionary.cs | 124 ++++++++++++++++++ .../ConcurrentDictionary/CdCharDictionary.cs | 124 ++++++++++++++++++ .../CdDecimalDictionary.cs | 124 ++++++++++++++++++ .../CdDoubleDictionary.cs | 124 ++++++++++++++++++ .../ConcurrentDictionary/CdFloatDictionary.cs | 124 ++++++++++++++++++ .../CdIntegerDictionary.cs | 124 ++++++++++++++++++ .../ConcurrentDictionary/CdLongDictionary.cs | 124 ++++++++++++++++++ .../ConcurrentDictionary/CdShortDictionary.cs | 124 ++++++++++++++++++ .../CdStringDictionary.cs | 4 +- 9 files changed, 994 insertions(+), 2 deletions(-) create mode 100644 TYLDDB/Utils/FastCache/ConcurrentDictionary/CdBooleanDictionary.cs create mode 100644 TYLDDB/Utils/FastCache/ConcurrentDictionary/CdCharDictionary.cs create mode 100644 TYLDDB/Utils/FastCache/ConcurrentDictionary/CdDecimalDictionary.cs create mode 100644 TYLDDB/Utils/FastCache/ConcurrentDictionary/CdDoubleDictionary.cs create mode 100644 TYLDDB/Utils/FastCache/ConcurrentDictionary/CdFloatDictionary.cs create mode 100644 TYLDDB/Utils/FastCache/ConcurrentDictionary/CdIntegerDictionary.cs create mode 100644 TYLDDB/Utils/FastCache/ConcurrentDictionary/CdLongDictionary.cs create mode 100644 TYLDDB/Utils/FastCache/ConcurrentDictionary/CdShortDictionary.cs diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdBooleanDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdBooleanDictionary.cs new file mode 100644 index 0000000..9a50a8f --- /dev/null +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdBooleanDictionary.cs @@ -0,0 +1,124 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.ConcurrentDictionary +{ + /// + /// Use concurrent dictionaries to achieve high concurrency stability.
+ /// 使用并发词典来实现高并发的稳定性。 + ///
+ public class CdBooleanDictionary + { + /// + /// Thread-safe dictionary to store cache data.
+ /// 线程安全的字典,用于存储缓存数据。 + ///
+ private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual bool GetByKey(string key) + { + _cache.TryGetValue(key, out var value); + return value; + } + + /// + /// Asynchronous method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) => await Task.FromResult(GetByKey(key)); + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual List GetKeysByValue(bool value) + { + var keys = new List(); + foreach (var kvp in _cache) + { + if (kvp.Value == value) + { + keys.Add(kvp.Key); + } + } + return keys; + } + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual async Task> GetKeysByValueAsync(bool value) => await Task.FromResult(GetKeysByValue(value)); + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual bool Set(string key, bool value) + { + // Using AddOrUpdate to ensure atomic insert or update operation + _cache.AddOrUpdate(key, value, (existingKey, existingValue) => value); + return true; + } + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual async Task SetAsync(string key, bool value) => await Task.FromResult(Set(key, value)); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual bool RemoveByKey(string key) => _cache.TryRemove(key, out _); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual async Task RemoveByKeyAsync(string key) => await Task.FromResult(RemoveByKey(key)); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual void Clear() => _cache.Clear(); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual async Task ClearAsync() => await Task.Run(() => Clear()); + + /// + /// Get all cache entries as a dictionary.
+ /// 获取所有缓存项,返回字典。 + ///
+ /// All cache entries as a dictionary.
所有缓存项的字典。
+ public virtual Dictionary GetAllCache() => new Dictionary(_cache); + } +} diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdCharDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdCharDictionary.cs new file mode 100644 index 0000000..9e27136 --- /dev/null +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdCharDictionary.cs @@ -0,0 +1,124 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.ConcurrentDictionary +{ + /// + /// Use concurrent dictionaries to achieve high concurrency stability.
+ /// 使用并发词典来实现高并发的稳定性。 + ///
+ public class CdCharDictionary + { + /// + /// Thread-safe dictionary to store cache data.
+ /// 线程安全的字典,用于存储缓存数据。 + ///
+ private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual char GetByKey(string key) + { + _cache.TryGetValue(key, out var value); + return value; + } + + /// + /// Asynchronous method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) => await Task.FromResult(GetByKey(key)); + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual List GetKeysByValue(char value) + { + var keys = new List(); + foreach (var kvp in _cache) + { + if (kvp.Value == value) + { + keys.Add(kvp.Key); + } + } + return keys; + } + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual async Task> GetKeysByValueAsync(char value) => await Task.FromResult(GetKeysByValue(value)); + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual bool Set(string key, char value) + { + // Using AddOrUpdate to ensure atomic insert or update operation + _cache.AddOrUpdate(key, value, (existingKey, existingValue) => value); + return true; + } + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual async Task SetAsync(string key, char value) => await Task.FromResult(Set(key, value)); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual bool RemoveByKey(string key) => _cache.TryRemove(key, out _); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual async Task RemoveByKeyAsync(string key) => await Task.FromResult(RemoveByKey(key)); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual void Clear() => _cache.Clear(); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual async Task ClearAsync() => await Task.Run(() => Clear()); + + /// + /// Get all cache entries as a dictionary.
+ /// 获取所有缓存项,返回字典。 + ///
+ /// All cache entries as a dictionary.
所有缓存项的字典。
+ public virtual Dictionary GetAllCache() => new Dictionary(_cache); + } +} diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdDecimalDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdDecimalDictionary.cs new file mode 100644 index 0000000..aa0a9d5 --- /dev/null +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdDecimalDictionary.cs @@ -0,0 +1,124 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.ConcurrentDictionary +{ + /// + /// Use concurrent dictionaries to achieve high concurrency stability.
+ /// 使用并发词典来实现高并发的稳定性。 + ///
+ public class CdDecimalDictionary + { + /// + /// Thread-safe dictionary to store cache data.
+ /// 线程安全的字典,用于存储缓存数据。 + ///
+ private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual decimal GetByKey(string key) + { + _cache.TryGetValue(key, out var value); + return value; + } + + /// + /// Asynchronous method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) => await Task.FromResult(GetByKey(key)); + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual List GetKeysByValue(decimal value) + { + var keys = new List(); + foreach (var kvp in _cache) + { + if (kvp.Value == value) + { + keys.Add(kvp.Key); + } + } + return keys; + } + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual async Task> GetKeysByValueAsync(decimal value) => await Task.FromResult(GetKeysByValue(value)); + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual bool Set(string key, decimal value) + { + // Using AddOrUpdate to ensure atomic insert or update operation + _cache.AddOrUpdate(key, value, (existingKey, existingValue) => value); + return true; + } + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual async Task SetAsync(string key, decimal value) => await Task.FromResult(Set(key, value)); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual bool RemoveByKey(string key) => _cache.TryRemove(key, out _); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual async Task RemoveByKeyAsync(string key) => await Task.FromResult(RemoveByKey(key)); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual void Clear() => _cache.Clear(); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual async Task ClearAsync() => await Task.Run(() => Clear()); + + /// + /// Get all cache entries as a dictionary.
+ /// 获取所有缓存项,返回字典。 + ///
+ /// All cache entries as a dictionary.
所有缓存项的字典。
+ public virtual Dictionary GetAllCache() => new Dictionary(_cache); + } +} diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdDoubleDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdDoubleDictionary.cs new file mode 100644 index 0000000..c2c09e7 --- /dev/null +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdDoubleDictionary.cs @@ -0,0 +1,124 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.ConcurrentDictionary +{ + /// + /// Use concurrent dictionaries to achieve high concurrency stability.
+ /// 使用并发词典来实现高并发的稳定性。 + ///
+ public class CdDoubleDictionary + { + /// + /// Thread-safe dictionary to store cache data.
+ /// 线程安全的字典,用于存储缓存数据。 + ///
+ private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual double GetByKey(string key) + { + _cache.TryGetValue(key, out var value); + return value; + } + + /// + /// Asynchronous method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) => await Task.FromResult(GetByKey(key)); + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual List GetKeysByValue(double value) + { + var keys = new List(); + foreach (var kvp in _cache) + { + if (kvp.Value == value) + { + keys.Add(kvp.Key); + } + } + return keys; + } + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual async Task> GetKeysByValueAsync(double value) => await Task.FromResult(GetKeysByValue(value)); + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual bool Set(string key, double value) + { + // Using AddOrUpdate to ensure atomic insert or update operation + _cache.AddOrUpdate(key, value, (existingKey, existingValue) => value); + return true; + } + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual async Task SetAsync(string key, double value) => await Task.FromResult(Set(key, value)); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual bool RemoveByKey(string key) => _cache.TryRemove(key, out _); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual async Task RemoveByKeyAsync(string key) => await Task.FromResult(RemoveByKey(key)); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual void Clear() => _cache.Clear(); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual async Task ClearAsync() => await Task.Run(() => Clear()); + + /// + /// Get all cache entries as a dictionary.
+ /// 获取所有缓存项,返回字典。 + ///
+ /// All cache entries as a dictionary.
所有缓存项的字典。
+ public virtual Dictionary GetAllCache() => new Dictionary(_cache); + } +} diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdFloatDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdFloatDictionary.cs new file mode 100644 index 0000000..bed0e42 --- /dev/null +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdFloatDictionary.cs @@ -0,0 +1,124 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.ConcurrentDictionary +{ + /// + /// Use concurrent dictionaries to achieve high concurrency stability.
+ /// 使用并发词典来实现高并发的稳定性。 + ///
+ public class CdFloatDictionary + { + /// + /// Thread-safe dictionary to store cache data.
+ /// 线程安全的字典,用于存储缓存数据。 + ///
+ private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual float GetByKey(string key) + { + _cache.TryGetValue(key, out var value); + return value; + } + + /// + /// Asynchronous method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) => await Task.FromResult(GetByKey(key)); + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual List GetKeysByValue(float value) + { + var keys = new List(); + foreach (var kvp in _cache) + { + if (kvp.Value == value) + { + keys.Add(kvp.Key); + } + } + return keys; + } + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual async Task> GetKeysByValueAsync(float value) => await Task.FromResult(GetKeysByValue(value)); + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual bool Set(string key, float value) + { + // Using AddOrUpdate to ensure atomic insert or update operation + _cache.AddOrUpdate(key, value, (existingKey, existingValue) => value); + return true; + } + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual async Task SetAsync(string key, float value) => await Task.FromResult(Set(key, value)); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual bool RemoveByKey(string key) => _cache.TryRemove(key, out _); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual async Task RemoveByKeyAsync(string key) => await Task.FromResult(RemoveByKey(key)); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual void Clear() => _cache.Clear(); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual async Task ClearAsync() => await Task.Run(() => Clear()); + + /// + /// Get all cache entries as a dictionary.
+ /// 获取所有缓存项,返回字典。 + ///
+ /// All cache entries as a dictionary.
所有缓存项的字典。
+ public virtual Dictionary GetAllCache() => new Dictionary(_cache); + } +} diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdIntegerDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdIntegerDictionary.cs new file mode 100644 index 0000000..feb3f2f --- /dev/null +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdIntegerDictionary.cs @@ -0,0 +1,124 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.ConcurrentDictionary +{ + /// + /// Use concurrent dictionaries to achieve high concurrency stability.
+ /// 使用并发词典来实现高并发的稳定性。 + ///
+ public class CdIntegerDictionary + { + /// + /// Thread-safe dictionary to store cache data.
+ /// 线程安全的字典,用于存储缓存数据。 + ///
+ private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual int GetByKey(string key) + { + _cache.TryGetValue(key, out var value); + return value; + } + + /// + /// Asynchronous method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) => await Task.FromResult(GetByKey(key)); + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual List GetKeysByValue(int value) + { + var keys = new List(); + foreach (var kvp in _cache) + { + if (kvp.Value == value) + { + keys.Add(kvp.Key); + } + } + return keys; + } + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual async Task> GetKeysByValueAsync(int value) => await Task.FromResult(GetKeysByValue(value)); + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual bool Set(string key, int value) + { + // Using AddOrUpdate to ensure atomic insert or update operation + _cache.AddOrUpdate(key, value, (existingKey, existingValue) => value); + return true; + } + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual async Task SetAsync(string key, int value) => await Task.FromResult(Set(key, value)); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual bool RemoveByKey(string key) => _cache.TryRemove(key, out _); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual async Task RemoveByKeyAsync(string key) => await Task.FromResult(RemoveByKey(key)); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual void Clear() => _cache.Clear(); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual async Task ClearAsync() => await Task.Run(() => Clear()); + + /// + /// Get all cache entries as a dictionary.
+ /// 获取所有缓存项,返回字典。 + ///
+ /// All cache entries as a dictionary.
所有缓存项的字典。
+ public virtual Dictionary GetAllCache() => new Dictionary(_cache); + } +} diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdLongDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdLongDictionary.cs new file mode 100644 index 0000000..43656d6 --- /dev/null +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdLongDictionary.cs @@ -0,0 +1,124 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.ConcurrentDictionary +{ + /// + /// Use concurrent dictionaries to achieve high concurrency stability.
+ /// 使用并发词典来实现高并发的稳定性。 + ///
+ public class CdLongDictionary + { + /// + /// Thread-safe dictionary to store cache data.
+ /// 线程安全的字典,用于存储缓存数据。 + ///
+ private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual long GetByKey(string key) + { + _cache.TryGetValue(key, out var value); + return value; + } + + /// + /// Asynchronous method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) => await Task.FromResult(GetByKey(key)); + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual List GetKeysByValue(long value) + { + var keys = new List(); + foreach (var kvp in _cache) + { + if (kvp.Value == value) + { + keys.Add(kvp.Key); + } + } + return keys; + } + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual async Task> GetKeysByValueAsync(long value) => await Task.FromResult(GetKeysByValue(value)); + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual bool Set(string key, long value) + { + // Using AddOrUpdate to ensure atomic insert or update operation + _cache.AddOrUpdate(key, value, (existingKey, existingValue) => value); + return true; + } + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual async Task SetAsync(string key, long value) => await Task.FromResult(Set(key, value)); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual bool RemoveByKey(string key) => _cache.TryRemove(key, out _); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual async Task RemoveByKeyAsync(string key) => await Task.FromResult(RemoveByKey(key)); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual void Clear() => _cache.Clear(); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual async Task ClearAsync() => await Task.Run(() => Clear()); + + /// + /// Get all cache entries as a dictionary.
+ /// 获取所有缓存项,返回字典。 + ///
+ /// All cache entries as a dictionary.
所有缓存项的字典。
+ public virtual Dictionary GetAllCache() => new Dictionary(_cache); + } +} diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdShortDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdShortDictionary.cs new file mode 100644 index 0000000..8ad8464 --- /dev/null +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdShortDictionary.cs @@ -0,0 +1,124 @@ +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace TYLDDB.Utils.FastCache.ConcurrentDictionary +{ + /// + /// Use concurrent dictionaries to achieve high concurrency stability.
+ /// 使用并发词典来实现高并发的稳定性。 + ///
+ public class CdShortDictionary + { + /// + /// Thread-safe dictionary to store cache data.
+ /// 线程安全的字典,用于存储缓存数据。 + ///
+ private readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); + + /// + /// Synchronization method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual short GetByKey(string key) + { + _cache.TryGetValue(key, out var value); + return value; + } + + /// + /// Asynchronous method: Obtain the corresponding value by key.
+ /// 同步方法:根据键获取对应的值。 + ///
+ /// Key
键 + /// Value
+ public virtual async Task GetByKeyAsync(string key) => await Task.FromResult(GetByKey(key)); + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual List GetKeysByValue(short value) + { + var keys = new List(); + foreach (var kvp in _cache) + { + if (kvp.Value == value) + { + keys.Add(kvp.Key); + } + } + return keys; + } + + /// + /// Get a list of keys that correspond to a specific value.
+ /// 获取与指定值对应的所有键的列表。 + ///
+ /// Value to match
要匹配的值 + /// List of keys
键的列表
+ public virtual async Task> GetKeysByValueAsync(short value) => await Task.FromResult(GetKeysByValue(value)); + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual bool Set(string key, short value) + { + // Using AddOrUpdate to ensure atomic insert or update operation + _cache.AddOrUpdate(key, value, (existingKey, existingValue) => value); + return true; + } + + /// + /// Set a cache entry for a specified key.
+ /// 为指定键设置缓存项。 + ///
+ /// Key
键 + /// Value
值 + /// Whether the operation is successful.
操作是否成功。
+ public virtual async Task SetAsync(string key, short value) => await Task.FromResult(Set(key, value)); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual bool RemoveByKey(string key) => _cache.TryRemove(key, out _); + + /// + /// Remove a cache entry by its key.
+ /// 根据键移除缓存项。 + ///
+ /// Key
键 + /// Whether the removal is successful.
移除操作是否成功。
+ public virtual async Task RemoveByKeyAsync(string key) => await Task.FromResult(RemoveByKey(key)); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual void Clear() => _cache.Clear(); + + /// + /// Clear all cache entries.
+ /// 清空所有缓存项。 + ///
+ public virtual async Task ClearAsync() => await Task.Run(() => Clear()); + + /// + /// Get all cache entries as a dictionary.
+ /// 获取所有缓存项,返回字典。 + ///
+ /// All cache entries as a dictionary.
所有缓存项的字典。
+ public virtual Dictionary GetAllCache() => new Dictionary(_cache); + } +} diff --git a/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdStringDictionary.cs b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdStringDictionary.cs index c92e73d..a859eae 100644 --- a/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdStringDictionary.cs +++ b/TYLDDB/Utils/FastCache/ConcurrentDictionary/CdStringDictionary.cs @@ -5,8 +5,8 @@ namespace TYLDDB.Utils.FastCache.ConcurrentDictionary { /// - /// Use thread locks based on concurrent dictionaries to achieve high concurrency stability.
- /// 使用基于信号量的线程锁来实现高并发的稳定性。 + /// Use concurrent dictionaries to achieve high concurrency stability.
+ /// 使用并发词典来实现高并发的稳定性。 ///
public class CdStringDictionary { From 0dda95213992fb8d537a7e92ee6790dfb0372e05 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 6 Jan 2025 14:54:50 +0800 Subject: [PATCH 49/52] bugs: fix proj file --- TimeRecord/TimeRecord.csproj | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/TimeRecord/TimeRecord.csproj b/TimeRecord/TimeRecord.csproj index 58f574d..65845ec 100644 --- a/TimeRecord/TimeRecord.csproj +++ b/TimeRecord/TimeRecord.csproj @@ -5,13 +5,5 @@ enable enable - -<<<<<<<< HEAD:TimeRecord/TimeRecord.csproj -======== - - - - - ->>>>>>>> cdf9c1039cfeae32fce9aac87ceb4ce2409ec22d:TYLDDB.Utils.FastCache.Test/TYLDDB.Utils.FastCache.Test.csproj + From 296902782602b7e176ed0e224e9b2a057ce3f41b Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 6 Jan 2025 15:10:15 +0800 Subject: [PATCH 50/52] =?UTF-8?q?style:=20=E6=B7=BB=E5=8A=A0=E6=8D=A2?= =?UTF-8?q?=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/Basic/Exception.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/TYLDDB/Basic/Exception.cs b/TYLDDB/Basic/Exception.cs index c354060..0d7924d 100644 --- a/TYLDDB/Basic/Exception.cs +++ b/TYLDDB/Basic/Exception.cs @@ -14,6 +14,7 @@ public class TylddbException : Exception /// public TylddbException(string message) : base(message) { } } + /// /// File opening failure
/// 文件打开失败 @@ -26,6 +27,7 @@ public class FileOpenFailException : TylddbException ///
public FileOpenFailException(string message) : base(message) { } } + /// /// File read failure
/// 文件读取失败 @@ -38,6 +40,7 @@ public class FileReadingFailException : TylddbException ///
public FileReadingFailException(string message) : base(message) { } } + /// /// File not found
/// 文件未找到 @@ -50,6 +53,7 @@ public class FileNotFoundException : TylddbException ///
public FileNotFoundException(string message) : base(message) { } } + /// /// The file path is null or space
/// 文件路径为null或空白 @@ -62,6 +66,7 @@ public class FilePathIsNullOrWhiteSpace : TylddbException ///
public FilePathIsNullOrWhiteSpace(string message) : base(message) { } } + /// /// Incorrect or invalid data
/// 错误或无效的数据 @@ -74,6 +79,7 @@ public class InvalidDataException : TylddbException ///
public InvalidDataException(string message) : base(message) { } } + /// /// Database not found
/// 未找到数据库 @@ -86,6 +92,7 @@ public class DatabaseNotFoundException : TylddbException ///
public DatabaseNotFoundException(string message) : base(message) { } } + /// /// Description Failed to obtain the database content
/// 数据库内容获取失败 From b43787de7311b5006a03dc4b5ca7281fcaf19e4b Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 6 Jan 2025 15:13:48 +0800 Subject: [PATCH 51/52] =?UTF-8?q?refactor:=20=E4=BC=98=E5=8C=96=E5=AE=9E?= =?UTF-8?q?=E4=BE=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TYLDDB/TYLDDB.cs | 46 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/TYLDDB/TYLDDB.cs b/TYLDDB/TYLDDB.cs index cdc8d6a..5370b06 100644 --- a/TYLDDB/TYLDDB.cs +++ b/TYLDDB/TYLDDB.cs @@ -20,7 +20,29 @@ public class LDDB ///
public LDDB() { - // NOTHING HERE! + database = new Database(); // 实例化数据库操作类 + + // 实例化并发词典 + cdStringDictionary = new CdStringDictionary(); + cdShortDictionary = new CdShortDictionary(); + cdLongDictionary = new CdLongDictionary(); + cdIntegerDictionary = new CdIntegerDictionary(); + cdFloatDictionary = new CdFloatDictionary(); + cdDoubleDictionary = new CdDoubleDictionary(); + cdDecimalDictionary = new CdDecimalDictionary(); + cdCharDictionary = new CdCharDictionary(); + cdBooleanDictionary = new CdBooleanDictionary(); + + // 实例化信号词典 + stlStringDictionary = new StlStringDictionary(); + stlShortDictionary = new StlShortDictionary(); + stlLongDictionary = new StlLongDictionary(); + stlIntegerDictionary = new StlIntegerDictionary(); + stlFloatDictionary = new StlFloatDictionary(); + stlDoubleDictionary = new StlDoubleDictionary(); + stlDecimalDictionary = new StlDecimalDictionary(); + stlCharDictionary = new StlCharDictionary(); + stlBooleanDictionary = new StlBooleanDictionary(); } ///////////////////////////////////////////////////// 私有字段 @@ -29,9 +51,25 @@ public LDDB() private string _database; // 存储正在访问的数据库 private string _databaseContent; // 存储数据库内容 private bool _isRead = false; // 是否已调用读取文件 - private Database database = new Database(); - private CdStringDictionary cdStringDictionary = new CdStringDictionary(); - private StlStringDictionary StlStringDictionary = new StlStringDictionary(); + private Database database; + private CdStringDictionary cdStringDictionary; + private CdShortDictionary cdShortDictionary; + private CdLongDictionary cdLongDictionary; + private CdIntegerDictionary cdIntegerDictionary; + private CdFloatDictionary cdFloatDictionary; + private CdDoubleDictionary cdDoubleDictionary; + private CdDecimalDictionary cdDecimalDictionary; + private CdCharDictionary cdCharDictionary; + private CdBooleanDictionary cdBooleanDictionary; + private StlStringDictionary stlStringDictionary; + private StlShortDictionary stlShortDictionary; + private StlLongDictionary stlLongDictionary; + private StlIntegerDictionary stlIntegerDictionary; + private StlFloatDictionary stlFloatDictionary; + private StlDoubleDictionary stlDoubleDictionary; + private StlDecimalDictionary stlDecimalDictionary; + private StlCharDictionary stlCharDictionary; + private StlBooleanDictionary stlBooleanDictionary; ///////////////////////////////////////////////////// 公开字段 /// From 0cedb69638637158f49e8a657f28c817454b7a32 Mon Sep 17 00:00:00 2001 From: Grey Wind Date: Mon, 6 Jan 2025 15:19:04 +0800 Subject: [PATCH 52/52] Update TYLDDB.csproj --- TYLDDB/TYLDDB.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index b470d6c..3c0d91e 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -4,7 +4,7 @@ netstandard2.1;net6.0;net8.0;net9.0 True TYLDDB.NET - 1.0.0-alpha.4 + 1.0.0-alpha.3p TYLDDB-Project LICENSE True