diff --git a/TYLDDB.Test/Program.cs b/TYLDDB.Test/Program.cs index ada0a5c..5f4d0b1 100644 --- a/TYLDDB.Test/Program.cs +++ b/TYLDDB.Test/Program.cs @@ -4,9 +4,12 @@ string dbFilePath = "./example.lddb"; List testData = []; +#region 实例化 ///////////////////////////////////////////////////////////////////////////////////////////////////////// 实例化 var lddb = new LDDB(); +#endregion +#region 读取文件 ///////////////////////////////////////////////////////////////////////////////////////////////////////// 读取文件 HighPrecisionTimer readDbTimer = new(); // 从发起读取文件到成功读取的总时间 lddb.FilePath = dbFilePath; @@ -14,7 +17,9 @@ lddb.ReadingFile(); readDbTimer.Stop(); WriteTime("从发起读取文件指令到成功读取的总时间为: ", readDbTimer.ElapsedMilliseconds()); +#endregion +#region 读取数据库 ///////////////////////////////////////////////////////////////////////////////////////////////////////// 读取数据库 HighPrecisionTimer loadDbTimer = new(); // 从发起读取数据库到成功返回读取内容的总时间 loadDbTimer.Start(); @@ -29,7 +34,9 @@ Console.WriteLine(lddb.GetLoadingDatabaseContent()); // 输出database1内容 loadDbV2Timer.Stop(); WriteTime("从发起读取数据库指令到成功返回读取内容的总时间为(V2): ", loadDbV2Timer.ElapsedMilliseconds()); +#endregion +#region 获取所有数据库名称 ///////////////////////////////////////////////////////////////////////////////////////////////////////// 获取所有数据库名称 HighPrecisionTimer readAllDbNameTimer = new(); // 从发起读取数据库名称到成功返回读取内容的总时间 readAllDbNameTimer.Start(); @@ -43,18 +50,25 @@ } } WriteTime("从发起读取数据库名称到成功返回读取内容的总时间为: ", readAllDbNameTimer.ElapsedMilliseconds()); +#endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////// 数据库解析缓存 -HighPrecisionTimer parseDbTimer = new(); // 从发起解析文件到成功解析并写入缓存的总时间(同步) +HighPrecisionTimer parseDbTimer = new(); parseDbTimer.Start(); -await lddb.Parse(); +await lddb.Parse_V1(); parseDbTimer.Stop(); -WriteTime("从发起解析文件到成功解析并写入缓存的总时间(同步): ", parseDbTimer.ElapsedMilliseconds()); -HighPrecisionTimer parseDbTimerAsync = new(); // 从发起解析文件到成功解析并写入缓存的总时间(异步) +WriteTime("解析文件并写入缓存V1(同步): ", parseDbTimer.ElapsedMilliseconds()); +HighPrecisionTimer parseDbTimerAsync = new(); parseDbTimerAsync.Start(); -await lddb.ParseAsync(); +await lddb.ParseAsync_V1(); parseDbTimerAsync.Stop(); -WriteTime("从发起解析文件到成功解析并写入缓存的总时间(异步): ", parseDbTimerAsync.ElapsedMilliseconds()); +WriteTime("解析文件并写入缓存V1(异步): ", parseDbTimerAsync.ElapsedMilliseconds()); + +//HighPrecisionTimer parseDbV2Timer = new(); +//parseDbV2Timer.Start(); +//lddb.Parse_V2(); +//parseDbV2Timer.Stop(); +//WriteTime("解析文件并写入缓存V1(同步): ", parseDbV2Timer.ElapsedMilliseconds()); ///////////////////////////////////////////////////////////////////////////////////////////////////////// 并发词典数据库全类型同步搜寻 HighPrecisionTimer allTypeSearchFromConcurrentDictionaryTimer = new(); diff --git a/TYLDDB/Basic/Exception.cs b/TYLDDB/Basic/Exception.cs deleted file mode 100644 index 0d7924d..0000000 --- a/TYLDDB/Basic/Exception.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System; - -namespace TYLDDB.Basic -{ - /// - /// The main error module, most of them use this
- /// 主要的错误模块,大部分都使用这个 - ///
- public class TylddbException : Exception - { - /// - /// The main error module, most of them use this
- /// 主要的错误模块,大部分都使用这个 - ///
- public TylddbException(string message) : base(message) { } - } - - /// - /// File opening failure
- /// 文件打开失败 - ///
- public class FileOpenFailException : TylddbException - { - /// - /// File opening failure
- /// 文件打开失败 - ///
- public FileOpenFailException(string message) : base(message) { } - } - - /// - /// File read failure
- /// 文件读取失败 - ///
- public class FileReadingFailException : TylddbException - { - /// - /// File read failure
- /// 文件读取失败 - ///
- public FileReadingFailException(string message) : base(message) { } - } - - /// - /// File not found
- /// 文件未找到 - ///
- public class FileNotFoundException : TylddbException - { - /// - /// File not found
- /// 文件未找到 - ///
- public FileNotFoundException(string message) : base(message) { } - } - - /// - /// The file path is null or space
- /// 文件路径为null或空白 - ///
- public class FilePathIsNullOrWhiteSpace : TylddbException - { - /// - /// The file path is null or space
- /// 文件路径为null或空白 - ///
- public FilePathIsNullOrWhiteSpace(string message) : base(message) { } - } - - /// - /// Incorrect or invalid data
- /// 错误或无效的数据 - ///
- public class InvalidDataException : TylddbException - { - /// - /// Incorrect or invalid data
- /// 错误或无效的数据 - ///
- public InvalidDataException(string message) : base(message) { } - } - - /// - /// Database not found
- /// 未找到数据库 - ///
- public class DatabaseNotFoundException : TylddbException - { - /// - /// Database not found
- /// 未找到数据库 - ///
- public DatabaseNotFoundException(string message) : base(message) { } - } - - /// - /// Description Failed to obtain the database content
- /// 数据库内容获取失败 - ///
- public class GetDatabaseContentErrorException : TylddbException - { - /// - /// Description Failed to obtain the database content
- /// 数据库内容获取失败 - ///
- public GetDatabaseContentErrorException(string message) : base(message) { } - } -} diff --git a/TYLDDB/Basic/Exception/DatabaseException.cs b/TYLDDB/Basic/Exception/DatabaseException.cs new file mode 100644 index 0000000..5f0d9f9 --- /dev/null +++ b/TYLDDB/Basic/Exception/DatabaseException.cs @@ -0,0 +1,28 @@ +namespace TYLDDB.Basic.Exception +{ + /// + /// Database not found
+ /// 未找到数据库 + ///
+ public class DatabaseNotFoundException : TylddbException + { + /// + /// Database not found
+ /// 未找到数据库 + ///
+ public DatabaseNotFoundException(string message) : base(message) { } + } + + /// + /// Description Failed to obtain the database content
+ /// 数据库内容获取失败 + ///
+ public class GetDatabaseContentErrorException : TylddbException + { + /// + /// Description Failed to obtain the database content
+ /// 数据库内容获取失败 + ///
+ public GetDatabaseContentErrorException(string message) : base(message) { } + } +} diff --git a/TYLDDB/Basic/Exception/FileException.cs b/TYLDDB/Basic/Exception/FileException.cs new file mode 100644 index 0000000..b8d1c75 --- /dev/null +++ b/TYLDDB/Basic/Exception/FileException.cs @@ -0,0 +1,54 @@ +namespace TYLDDB.Basic.Exception +{ + /// + /// File opening failure
+ /// 文件打开失败 + ///
+ public class FileOpenFailException : FileException + { + /// + /// File opening failure
+ /// 文件打开失败 + ///
+ public FileOpenFailException(string message) : base(message) { } + } + + /// + /// File read failure
+ /// 文件读取失败 + ///
+ public class FileReadingFailException : FileException + { + /// + /// File read failure
+ /// 文件读取失败 + ///
+ public FileReadingFailException(string message) : base(message) { } + } + + /// + /// File not found
+ /// 文件未找到 + ///
+ public class FileNotFoundException : FileException + { + /// + /// File not found
+ /// 文件未找到 + ///
+ public FileNotFoundException(string message) : base(message) { } + } + + /// + /// The file path is null or space
+ /// 文件路径为null或空白 + ///
+ public class FilePathIsNullOrWhiteSpace : FileException + { + /// + /// The file path is null or space
+ /// 文件路径为null或空白 + ///
+ public FilePathIsNullOrWhiteSpace(string message) : base(message) { } + } +} diff --git a/TYLDDB/Basic/Exception/TripleDictionaryException.cs b/TYLDDB/Basic/Exception/TripleDictionaryException.cs new file mode 100644 index 0000000..28fec7b --- /dev/null +++ b/TYLDDB/Basic/Exception/TripleDictionaryException.cs @@ -0,0 +1,16 @@ +namespace TYLDDB.Basic.Exception +{ +#if NET8_0_OR_GREATER + /// + /// An exception class to the three-value dictionary.
+ /// 三值字典的例外类。 + ///
+ public class TripleDictionaryException(string message) : DictionaryException(message) { } + + /// + /// The specified key was not found.
+ /// 未找到指定的键。 + ///
+ public class TripleDictionaryKeyNotFoundException(string message) : TripleDictionaryException(message) { } +#endif +} diff --git a/TYLDDB/Basic/Exception/TylddbException.cs b/TYLDDB/Basic/Exception/TylddbException.cs new file mode 100644 index 0000000..f2b382e --- /dev/null +++ b/TYLDDB/Basic/Exception/TylddbException.cs @@ -0,0 +1,94 @@ +namespace TYLDDB.Basic.Exception +{ + /// + /// The main error module, most of them use this
+ /// 主要的错误模块,大部分都使用这个 + ///
+ public class TylddbException : System.Exception + { + /// + /// The main error module, most of them use this
+ /// 主要的错误模块,大部分都使用这个 + ///
+ public TylddbException(string message) : base(message) { } + } + + /// + /// Error module about file.
+ /// 有关文件的错误模块。 + ///
+ public class FileException : TylddbException + { + /// + /// Error module about file.
+ /// 有关文件的错误模块。 + ///
+ public FileException(string message) : base(message) { } + } + + /// + /// Error module about write file function.
+ /// 有关写入文件功能的错误模块。 + ///
+ public class WriteException : TylddbException + { + /// + /// Error module about write file function.
+ /// 有关写入文件功能的错误模块。 + ///
+ public WriteException(string message) : base(message) { } + } + + /// + /// Error module about write file function.
+ /// 有关写入文件功能的错误模块。 + ///
+ public class ReadException : TylddbException + { + /// + /// Error module about write file function.
+ /// 有关写入文件功能的错误模块。 + ///
+ public ReadException(string message) : base(message) { } + } + + /// + /// Error module about database.
+ /// 有关数据库的错误模块。 + ///
+ public class DatabaseException : TylddbException + { + /// + /// Error module about database.
+ /// 有关数据库的错误模块。 + ///
+ public DatabaseException(string message) : base(message) { } + } + + /// + /// Dictionary exception class.
+ /// 字典的错误类。 + ///
+ public class DictionaryException : TylddbException + { + /// + /// Dictionary exception class.
+ /// 字典的错误类。 + ///
+ public DictionaryException(string message) : base(message) { } + } + + // 未分类的错误 + /// + /// Incorrect or invalid data
+ /// 错误或无效的数据 + ///
+ public class InvalidDataException : TylddbException + { + /// + /// Incorrect or invalid data
+ /// 错误或无效的数据 + ///
+ public InvalidDataException(string message) : base(message) { } + } +} diff --git a/TYLDDB/Basic/Exception/WriteException.cs b/TYLDDB/Basic/Exception/WriteException.cs new file mode 100644 index 0000000..5e593ae --- /dev/null +++ b/TYLDDB/Basic/Exception/WriteException.cs @@ -0,0 +1,28 @@ +namespace TYLDDB.Basic.Exception +{ + /// + /// Error database content to file.
+ /// 写入数据库内容到文件时的错误。 + ///
+ public class WriteStringToFileException : WriteException + { + /// + /// Error database content to file.
+ /// 写入数据库内容到文件时的错误。 + ///
+ public WriteStringToFileException(string message) : base(message) { } + } + + /// + /// Block-writing error in database to file.
+ /// 分块写入数据库到文件的错误。 + ///
+ public class WriteStringToFileInChunksException : WriteException + { + /// + /// Block-writing error in database to file.
+ /// 分块写入数据库到文件的错误。 + ///
+ public WriteStringToFileInChunksException(string message) : base(message) { } + } +} diff --git a/TYLDDB/Basic/TripleDictionary.cs b/TYLDDB/Basic/TripleDictionary.cs new file mode 100644 index 0000000..12ea9b1 --- /dev/null +++ b/TYLDDB/Basic/TripleDictionary.cs @@ -0,0 +1,187 @@ +using System.Collections.Generic; +using System; +using System.Collections.Concurrent; +using System.Linq; +using TYLDDB.Basic.Exception; + +namespace TYLDDB.Basic +{ +#if NET8_0_OR_GREATER + /// + /// Three-value dictionary.
+ /// 三值字典。 + ///
+ /// The data type of the value.
值的数据类型。
+ public class TripleDictionary + { + private readonly ConcurrentDictionary, TValue> _dictionary; + + /// + /// Three-value dictionary.
+ /// 三值字典。 + ///
+ public TripleDictionary() + { + _dictionary = new ConcurrentDictionary, TValue>(); + } + + /// + /// Add an element, only if the key for the combination does not exist.
+ /// 添加元素,只有当该组合的键不存在时才添加。 + ///
+ /// Data type.
数据类型。 + /// Key.
键。 + /// Value.
值。 + /// Whether the value is added successfully.
是否成功添加。
+ public bool Add(string type, string key, TValue value) + { + var keyTuple = new Tuple(type, key); + + // 检查是否已经存在相同的键组合 + if (_dictionary.ContainsKey(keyTuple)) + { + return false; // 如果已存在相同的键组合,返回 false 表示添加失败 + } + + // 如果没有该键组合,执行添加操作 + _dictionary[keyTuple] = value; + return true; // 添加成功 + } + + /// + /// Only values are updated, types and keys cannot be updated.
+ /// 只更新值,不能更新类型和键。 + ///
+ /// Data type.
数据类型。 + /// Key.
键。 + /// New value.
新值。 + /// Whether the update is successful.
是否成功更新。
+ public bool UpdateValue(string type, string key, TValue newValue) + { + var keyTuple = new Tuple(type, key); + + // 检查该键组合是否存在 + if (!_dictionary.ContainsKey(keyTuple)) + { + return false; // 如果不存在,返回 false + } + + // 如果存在,更新值 + _dictionary[keyTuple] = newValue; + return true; // 更新成功 + } + + /// + /// Get the element.
+ /// 获取元素。 + ///
+ /// Data type.
数据类型。 + /// Key.
键。 + /// Value.
值。
+ /// The specified key was not found.
未找到指定的键。
+ public TValue Get(string type, string key) + { + var keyTuple = new Tuple(type, key); + if (_dictionary.TryGetValue(keyTuple, out TValue value)) + { + return value; + } + else + { + throw new TripleDictionaryKeyNotFoundException("The key combination was not found."); + } + } + + /// + /// Checks whether the specified type and key combination are included.
+ /// 检查是否包含指定的类型和键组合。 + ///
+ /// Data type.
数据类型。 + /// Key.
键。 + /// Whether the key is included.
是否包含该键。
+ public bool ContainsKey(string type, string key) => _dictionary.ContainsKey(new Tuple(type, key)); + + /// + /// Deleting a certain type removes all the key values of the class.
+ /// 删除某个类型会删除该类型下的所有键值对。 + ///
+ /// Data type.
数据类型。 + /// Whether the data type is removed successfully.
是否成功移除该数据类型。
+ public bool RemoveType(string type) + { + var keysToRemove = _dictionary.Keys.Where(k => k.Item1 == type).ToList(); + + if (keysToRemove.Count == 0) + { + return false; // 如果该类型没有键值对,返回 false + } + + foreach (var key in keysToRemove) + { + _dictionary.TryRemove(key, out _); + } + return true; + } + + /// + /// Deletes the specified key and corresponding value from the specified type.
+ /// 删除指定类型中的指定键和对应的值。 + ///
+ /// Data type.
数据类型。 + /// Key.
键。 + /// Whether the key is successfully removed.
是否成功移除该键。
+ public bool RemoveKey(string type, string key) + { + var keyTuple = new Tuple(type, key); + + // 尝试移除指定的键值对 + if (_dictionary.TryRemove(keyTuple, out _)) + { + return true; // 删除成功 + } + else + { + return false; // 如果没有找到该键组合,返回 false + } + } + + /// + /// Removes the specified key and corresponding value from all types.
+ /// 删除所有类型中的指定键和对应的值。 + ///
+ /// Key.
键。 + /// Whether the key is successfully removed.
是否成功移除该键。
+ public bool RemoveKey(string key) + { + bool removed = false; + + // 查找所有包含该 Key 的项,并删除它们 + var keysToRemove = _dictionary.Where(entry => entry.Key.Item2 == key) + .Select(entry => entry.Key) + .ToList(); + + foreach (var keyTuple in keysToRemove) + { + if (_dictionary.TryRemove(keyTuple, out _)) + { + removed = true; + } + } + + return removed; // 如果至少删除了一个键值对,返回 true + } + + /// + /// Prints all types of key-value pairs.
+ /// 打印所有类型的键值对。 + ///
+ public void PrintAll() + { + foreach (var entry in _dictionary) + { + Console.WriteLine($"Type: {entry.Key.Item1}, Key: {entry.Key.Item2} -> Value: {entry.Value}"); + } + } + } +#endif +} diff --git a/TYLDDB/Parser/Parser.cs b/TYLDDB/Parser/V1.cs similarity index 99% rename from TYLDDB/Parser/Parser.cs rename to TYLDDB/Parser/V1.cs index a0d522d..82f7036 100644 --- a/TYLDDB/Parser/Parser.cs +++ b/TYLDDB/Parser/V1.cs @@ -9,7 +9,7 @@ namespace TYLDDB.Parser /// Data type parser.
/// 数据类型解析器。 /// - public class DataParser + public class DataParser_V1 { // 定义正则表达式来匹配键值对(类型::"key"="value") private readonly static string pattern = @"(\w+)\s*::\s*""([^""]+)""\s*=\s*""([^""]+)"";"; diff --git a/TYLDDB/TYLDDB.cs b/TYLDDB/TYLDDB.cs index e04cf39..93c1007 100644 --- a/TYLDDB/TYLDDB.cs +++ b/TYLDDB/TYLDDB.cs @@ -1,12 +1,7 @@ using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; -using TYLDDB.Basic; -using TYLDDB.Parser; +using TYLDDB.Basic.Exception; using TYLDDB.Utils; -using TYLDDB.Utils.Database; -using TYLDDB.Utils.FastCache.ConcurrentDictionary; -using TYLDDB.Utils.FastCache.SemaphoreThreadLock; namespace TYLDDB { @@ -14,67 +9,9 @@ namespace TYLDDB /// The core class of the database.
/// 数据库的核心类。 /// - public class LDDB + public partial class LDDB { - /// - /// Instantiate the LDDB class
- /// 实例化LDDB类 - ///
- public LDDB() - { - // 实例化数据库操作类 - database_v1 = new Database_V1(); - database_v2 = new Database_V2(); - - // 实例化并发词典 - 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(); - } - - ///////////////////////////////////////////////////// 私有字段 - private string _filePath; // 存储文件路径 - private string _fileContent; // 存储文件内容 - private string _databaseContent; // 存储数据库内容 - private Database_V1 database_v1; - private Database_V2 database_v2; - 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; - - ///////////////////////////////////////////////////// 公开字段 + #region 公开字段 /// /// Set the path where you want to read the file
/// 设置希望读取文件的路径 @@ -99,6 +36,9 @@ public string FilePath /// 当前文件内所有数据库的名称 ///
public List AllDatabaseName; + #endregion + + #region 方法 /// /// 验证文件路径是否为null或空 @@ -111,7 +51,7 @@ private static bool ValidateFilePath(string path) if (string.IsNullOrWhiteSpace(path)) { return false; - throw new FilePathIsNullOrWhiteSpace("文件路径不能为 null 或空白"); + throw new FilePathIsNullOrWhiteSpace("The file path cannot be null or blank."); } return true; } @@ -156,620 +96,6 @@ public void LoadDatabase_V2(string db) /// public void ReadAllDatabaseName() => AllDatabaseName = database_v1.GetDatabaseList(_fileContent); - /// - /// Reparse the entire database.
- /// 重新解析整个数据库。 - ///
- public async Task Parse() - { - // 创建多个任务,并使用 LongRunning 来确保每个任务在独立线程中运行 - - // ConcurrentDictionary - Task cdStringCacheTask = Task.Factory.StartNew(() => CdString(), TaskCreationOptions.LongRunning); - Task cdIntCacheTask = Task.Factory.StartNew(() => CdInt(), TaskCreationOptions.LongRunning); - Task cdShortCacheTask = Task.Factory.StartNew(() => CdShort(), TaskCreationOptions.LongRunning); - Task cdLongCacheTask = Task.Factory.StartNew(() => CdLong(), TaskCreationOptions.LongRunning); - Task cdFloatCacheTask = Task.Factory.StartNew(() => CdFloat(), TaskCreationOptions.LongRunning); - Task cdDoubleCacheTask = Task.Factory.StartNew(() => CdDouble(), TaskCreationOptions.LongRunning); - Task cdDecimalCacheTask = Task.Factory.StartNew(() => CdDecimal(), TaskCreationOptions.LongRunning); - Task cdCharCacheTask = Task.Factory.StartNew(() => CdChar(), TaskCreationOptions.LongRunning); - Task cdBoolCacheTask = Task.Factory.StartNew(() => CdBool(), TaskCreationOptions.LongRunning); - - // SemaphoreThreadLock - Task stlStringCacheTask = Task.Factory.StartNew(() => StlString(), TaskCreationOptions.LongRunning); - Task stlIntCacheTask = Task.Factory.StartNew(() => StlInt(), TaskCreationOptions.LongRunning); - Task stlShortCacheTask = Task.Factory.StartNew(() => StlShort(), TaskCreationOptions.LongRunning); - Task stlLongCacheTask = Task.Factory.StartNew(() => StlLong(), TaskCreationOptions.LongRunning); - Task stlFloatCacheTask = Task.Factory.StartNew(() => StlFloat(), TaskCreationOptions.LongRunning); - Task stlDoubleCacheTask = Task.Factory.StartNew(() => StlDouble(), TaskCreationOptions.LongRunning); - Task stlDecimalCacheTask = Task.Factory.StartNew(() => StlDecimal(), TaskCreationOptions.LongRunning); - Task stlCharCacheTask = Task.Factory.StartNew(() => StlChar(), TaskCreationOptions.LongRunning); - Task stlBoolCacheTask = Task.Factory.StartNew(() => StlBool(), TaskCreationOptions.LongRunning); - - // 等待所有任务完成 - await Task.WhenAll(cdStringCacheTask, - cdIntCacheTask, - cdShortCacheTask, - cdLongCacheTask, - cdFloatCacheTask, - cdDoubleCacheTask, - cdDecimalCacheTask, - cdCharCacheTask, - cdBoolCacheTask, - stlStringCacheTask, - stlIntCacheTask, - stlShortCacheTask, - stlLongCacheTask, - stlFloatCacheTask, - stlDoubleCacheTask, - stlDecimalCacheTask, - stlCharCacheTask, - stlBoolCacheTask); - - // ConcurrentDictionary - 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 对存储到缓存 - cdStringDictionary.Set(key, value); - } - } - void CdShort() - { - var dict = DataParser.ParseShort(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - cdShortDictionary.Set(key, value); - } - } - void CdLong() - { - var dict = DataParser.ParseLong(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - cdLongDictionary.Set(key, value); - } - } - void CdInt() - { - var dict = DataParser.ParseInt(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - cdIntegerDictionary.Set(key, value); - } - } - void CdFloat() - { - var dict = DataParser.ParseFloat(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - cdFloatDictionary.Set(key, value); - } - } - void CdDouble() - { - var dict = DataParser.ParseDouble(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - cdDoubleDictionary.Set(key, value); - } - } - void CdDecimal() - { - var dict = DataParser.ParseDecimal(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - cdDecimalDictionary.Set(key, value); - } - } - void CdChar() - { - var dict = DataParser.ParseChar(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - cdCharDictionary.Set(key, value); - } - } - void CdBool() - { - var dict = DataParser.ParseBoolean(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - cdBooleanDictionary.Set(key, value); - } - } - - // SemaphoreThreadLock - void StlString() - { - var dict = DataParser.ParseString(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - stlStringDictionary.Set(key, value); - } - } - void StlShort() - { - var dict = DataParser.ParseShort(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - stlShortDictionary.Set(key, value); - } - } - void StlLong() - { - var dict = DataParser.ParseLong(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - stlLongDictionary.Set(key, value); - } - } - void StlInt() - { - var dict = DataParser.ParseInt(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - stlIntegerDictionary.Set(key, value); - } - } - void StlFloat() - { - var dict = DataParser.ParseFloat(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - stlFloatDictionary.Set(key, value); - } - } - void StlDouble() - { - var dict = DataParser.ParseDouble(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - stlDoubleDictionary.Set(key, value); - } - } - void StlDecimal() - { - var dict = DataParser.ParseDecimal(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - stlDecimalDictionary.Set(key, value); - } - } - void StlChar() - { - var dict = DataParser.ParseChar(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - stlCharDictionary.Set(key, value); - } - } - void StlBool() - { - var dict = DataParser.ParseBoolean(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - stlBooleanDictionary.Set(key, value); - } - } - } - - /// - /// Reparse the entire database.
- /// 重新解析整个数据库。 - ///
- public async Task ParseAsync() - { - // 创建多个任务,并使用 LongRunning 来确保每个任务在独立线程中运行 - - // ConcurrentDictionary - Task cdStringCacheTask = Task.Factory.StartNew(() => CdString(), TaskCreationOptions.LongRunning); - Task cdIntCacheTask = Task.Factory.StartNew(() => CdInt(), TaskCreationOptions.LongRunning); - Task cdShortCacheTask = Task.Factory.StartNew(() => CdShort(), TaskCreationOptions.LongRunning); - Task cdLongCacheTask = Task.Factory.StartNew(() => CdLong(), TaskCreationOptions.LongRunning); - Task cdFloatCacheTask = Task.Factory.StartNew(() => CdFloat(), TaskCreationOptions.LongRunning); - Task cdDoubleCacheTask = Task.Factory.StartNew(() => CdDouble(), TaskCreationOptions.LongRunning); - Task cdDecimalCacheTask = Task.Factory.StartNew(() => CdDecimal(), TaskCreationOptions.LongRunning); - Task cdCharCacheTask = Task.Factory.StartNew(() => CdChar(), TaskCreationOptions.LongRunning); - Task cdBoolCacheTask = Task.Factory.StartNew(() => CdBool(), TaskCreationOptions.LongRunning); - - // SemaphoreThreadLock - Task stlStringCacheTask = Task.Factory.StartNew(() => StlString(), TaskCreationOptions.LongRunning); - Task stlIntCacheTask = Task.Factory.StartNew(() => StlInt(), TaskCreationOptions.LongRunning); - Task stlShortCacheTask = Task.Factory.StartNew(() => StlShort(), TaskCreationOptions.LongRunning); - Task stlLongCacheTask = Task.Factory.StartNew(() => StlLong(), TaskCreationOptions.LongRunning); - Task stlFloatCacheTask = Task.Factory.StartNew(() => StlFloat(), TaskCreationOptions.LongRunning); - Task stlDoubleCacheTask = Task.Factory.StartNew(() => StlDouble(), TaskCreationOptions.LongRunning); - Task stlDecimalCacheTask = Task.Factory.StartNew(() => StlDecimal(), TaskCreationOptions.LongRunning); - Task stlCharCacheTask = Task.Factory.StartNew(() => StlChar(), TaskCreationOptions.LongRunning); - Task stlBoolCacheTask = Task.Factory.StartNew(() => StlBool(), TaskCreationOptions.LongRunning); - - // 等待所有任务完成 - await Task.WhenAll(cdStringCacheTask, - cdIntCacheTask, - cdShortCacheTask, - cdLongCacheTask, - cdFloatCacheTask, - cdDoubleCacheTask, - cdDecimalCacheTask, - cdCharCacheTask, - cdBoolCacheTask, - stlStringCacheTask, - stlIntCacheTask, - stlShortCacheTask, - stlLongCacheTask, - stlFloatCacheTask, - stlDoubleCacheTask, - stlDecimalCacheTask, - stlCharCacheTask, - stlBoolCacheTask); - - // ConcurrentDictionary - 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 cdStringDictionary.SetAsync(key, value); - } - } - async void CdShort() - { - var dict = DataParser.ParseShort(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await cdShortDictionary.SetAsync(key, value); - } - } - async void CdLong() - { - var dict = DataParser.ParseLong(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await cdLongDictionary.SetAsync(key, value); - } - } - async void CdInt() - { - var dict = DataParser.ParseInt(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await cdIntegerDictionary.SetAsync(key, value); - } - } - async void CdFloat() - { - var dict = DataParser.ParseFloat(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await cdFloatDictionary.SetAsync(key, value); - } - } - async void CdDouble() - { - var dict = DataParser.ParseDouble(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await cdDoubleDictionary.SetAsync(key, value); - } - } - async void CdDecimal() - { - var dict = DataParser.ParseDecimal(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await cdDecimalDictionary.SetAsync(key, value); - } - } - async void CdChar() - { - var dict = DataParser.ParseChar(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await cdCharDictionary.SetAsync(key, value); - } - } - async void CdBool() - { - var dict = DataParser.ParseBoolean(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await cdBooleanDictionary.SetAsync(key, value); - } - } - - // SemaphoreThreadLock - async void StlString() - { - var dict = DataParser.ParseString(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await stlStringDictionary.SetAsync(key, value); - } - } - async void StlShort() - { - var dict = DataParser.ParseShort(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await stlShortDictionary.SetAsync(key, value); - } - } - async void StlLong() - { - var dict = DataParser.ParseLong(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await stlLongDictionary.SetAsync(key, value); - } - } - async void StlInt() - { - var dict = DataParser.ParseInt(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await stlIntegerDictionary.SetAsync(key, value); - } - } - async void StlFloat() - { - var dict = DataParser.ParseFloat(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await stlFloatDictionary.SetAsync(key, value); - } - } - async void StlDouble() - { - var dict = DataParser.ParseDouble(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await stlDoubleDictionary.SetAsync(key, value); - } - } - async void StlDecimal() - { - var dict = DataParser.ParseDecimal(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await stlDecimalDictionary.SetAsync(key, value); - } - } - async void StlChar() - { - var dict = DataParser.ParseChar(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await stlCharDictionary.SetAsync(key, value); - } - } - async void StlBool() - { - var dict = DataParser.ParseBoolean(_databaseContent); - - // 遍历 dict 中的每一项 - foreach (var kvp in dict) - { - var key = kvp.Key; // 获取第一个值 (key) - var value = kvp.Value; // 获取第二个值 (value) - - // 将 key-value 对存储到缓存 - await stlBooleanDictionary.SetAsync(key, value); - } - } - } - /// /// Finds the value associated with a given key from multiple types of concurrent dictionaries and returns all non-empty values as an array of strings.
/// 从多个类型的并发词典中查找与给定键相关的值,并将所有非空的值以字符串数组的形式返回。 @@ -823,5 +149,6 @@ public string[] AllTypeSearchFromSemaphoreThreadLock(string key) return resultArray; } + #endregion } } diff --git a/TYLDDB/TYLDDB.csproj b/TYLDDB/TYLDDB.csproj index 2ccd26d..d78d8fa 100644 --- a/TYLDDB/TYLDDB.csproj +++ b/TYLDDB/TYLDDB.csproj @@ -1,10 +1,10 @@ - + - netstandard2.1;net6.0;net8.0;net9.0 + netstandard2.1;net6.0;net7.0;net8.0;net9.0;net6.0-windows;net7.0-windows;net8.0-windows;net9.0-windows True TYLDDB.NET - 1.0.0-alpha.4pre1 + 1.0.0-alpha.4pre2 TYLDDB-Project LICENSE True @@ -19,8 +19,9 @@ DataBase QingYi-Studio README.md - Add a database parser (data type only, internal and distributed databases are not available). -Fast cache underlying interface optimization. + - Optimize error classes: Add more refined error handling and throwing. +- Allows you to customize the buffer size when reading files in blocks. +- Add a three-value dictionary (under test). diff --git a/TYLDDB/TYLDDB_Instantiation.cs b/TYLDDB/TYLDDB_Instantiation.cs new file mode 100644 index 0000000..8b6abb1 --- /dev/null +++ b/TYLDDB/TYLDDB_Instantiation.cs @@ -0,0 +1,45 @@ +using TYLDDB.Utils.Database; +using TYLDDB.Utils.FastCache.ConcurrentDictionary; +using TYLDDB.Utils.FastCache.SemaphoreThreadLock; + +namespace TYLDDB +{ + public partial class LDDB + { + /// + /// Instantiate the LDDB class
+ /// 实例化LDDB类 + ///
+ public LDDB() + { + #region 实例化数据库操作类 + database_v1 = new Database_V1(); + database_v2 = new Database_V2(); + #endregion + + #region 实例化并发词典 + 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(); + #endregion + + #region 实例化信号词典 + 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(); + #endregion + } + } +} diff --git a/TYLDDB/TYLDDB_Parse.cs b/TYLDDB/TYLDDB_Parse.cs new file mode 100644 index 0000000..876e2c6 --- /dev/null +++ b/TYLDDB/TYLDDB_Parse.cs @@ -0,0 +1,624 @@ +using System.Threading.Tasks; +using TYLDDB.Parser; + +namespace TYLDDB +{ + public partial class LDDB + { + /// + /// Reparse the entire database.
+ /// 重新解析整个数据库。 + ///
+ public async Task Parse_V1() + { + // 创建多个任务,并使用 LongRunning 来确保每个任务在独立线程中运行 + + #region 并发数据库任务 + Task cdStringCacheTask = Task.Factory.StartNew(() => CdString(), TaskCreationOptions.LongRunning); + Task cdIntCacheTask = Task.Factory.StartNew(() => CdInt(), TaskCreationOptions.LongRunning); + Task cdShortCacheTask = Task.Factory.StartNew(() => CdShort(), TaskCreationOptions.LongRunning); + Task cdLongCacheTask = Task.Factory.StartNew(() => CdLong(), TaskCreationOptions.LongRunning); + Task cdFloatCacheTask = Task.Factory.StartNew(() => CdFloat(), TaskCreationOptions.LongRunning); + Task cdDoubleCacheTask = Task.Factory.StartNew(() => CdDouble(), TaskCreationOptions.LongRunning); + Task cdDecimalCacheTask = Task.Factory.StartNew(() => CdDecimal(), TaskCreationOptions.LongRunning); + Task cdCharCacheTask = Task.Factory.StartNew(() => CdChar(), TaskCreationOptions.LongRunning); + Task cdBoolCacheTask = Task.Factory.StartNew(() => CdBool(), TaskCreationOptions.LongRunning); + #endregion + + #region 信号量数据库任务 + Task stlStringCacheTask = Task.Factory.StartNew(() => StlString(), TaskCreationOptions.LongRunning); + Task stlIntCacheTask = Task.Factory.StartNew(() => StlInt(), TaskCreationOptions.LongRunning); + Task stlShortCacheTask = Task.Factory.StartNew(() => StlShort(), TaskCreationOptions.LongRunning); + Task stlLongCacheTask = Task.Factory.StartNew(() => StlLong(), TaskCreationOptions.LongRunning); + Task stlFloatCacheTask = Task.Factory.StartNew(() => StlFloat(), TaskCreationOptions.LongRunning); + Task stlDoubleCacheTask = Task.Factory.StartNew(() => StlDouble(), TaskCreationOptions.LongRunning); + Task stlDecimalCacheTask = Task.Factory.StartNew(() => StlDecimal(), TaskCreationOptions.LongRunning); + Task stlCharCacheTask = Task.Factory.StartNew(() => StlChar(), TaskCreationOptions.LongRunning); + Task stlBoolCacheTask = Task.Factory.StartNew(() => StlBool(), TaskCreationOptions.LongRunning); + #endregion + + // 等待所有任务完成 + await Task.WhenAll(cdStringCacheTask, + cdIntCacheTask, + cdShortCacheTask, + cdLongCacheTask, + cdFloatCacheTask, + cdDoubleCacheTask, + cdDecimalCacheTask, + cdCharCacheTask, + cdBoolCacheTask, + stlStringCacheTask, + stlIntCacheTask, + stlShortCacheTask, + stlLongCacheTask, + stlFloatCacheTask, + stlDoubleCacheTask, + stlDecimalCacheTask, + stlCharCacheTask, + stlBoolCacheTask); + + // ConcurrentDictionary + void CdString() + { + var dict = DataParser_V1.ParseString(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + cdStringDictionary.Set(key, value); + } + } + void CdShort() + { + var dict = DataParser_V1.ParseShort(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + cdShortDictionary.Set(key, value); + } + } + void CdLong() + { + var dict = DataParser_V1.ParseLong(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + cdLongDictionary.Set(key, value); + } + } + void CdInt() + { + var dict = DataParser_V1.ParseInt(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + cdIntegerDictionary.Set(key, value); + } + } + void CdFloat() + { + var dict = DataParser_V1.ParseFloat(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + cdFloatDictionary.Set(key, value); + } + } + void CdDouble() + { + var dict = DataParser_V1.ParseDouble(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + cdDoubleDictionary.Set(key, value); + } + } + void CdDecimal() + { + var dict = DataParser_V1.ParseDecimal(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + cdDecimalDictionary.Set(key, value); + } + } + void CdChar() + { + var dict = DataParser_V1.ParseChar(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + cdCharDictionary.Set(key, value); + } + } + void CdBool() + { + var dict = DataParser_V1.ParseBoolean(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + cdBooleanDictionary.Set(key, value); + } + } + + // SemaphoreThreadLock + void StlString() + { + var dict = DataParser_V1.ParseString(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + stlStringDictionary.Set(key, value); + } + } + void StlShort() + { + var dict = DataParser_V1.ParseShort(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + stlShortDictionary.Set(key, value); + } + } + void StlLong() + { + var dict = DataParser_V1.ParseLong(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + stlLongDictionary.Set(key, value); + } + } + void StlInt() + { + var dict = DataParser_V1.ParseInt(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + stlIntegerDictionary.Set(key, value); + } + } + void StlFloat() + { + var dict = DataParser_V1.ParseFloat(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + stlFloatDictionary.Set(key, value); + } + } + void StlDouble() + { + var dict = DataParser_V1.ParseDouble(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + stlDoubleDictionary.Set(key, value); + } + } + void StlDecimal() + { + var dict = DataParser_V1.ParseDecimal(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + stlDecimalDictionary.Set(key, value); + } + } + void StlChar() + { + var dict = DataParser_V1.ParseChar(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + stlCharDictionary.Set(key, value); + } + } + void StlBool() + { + var dict = DataParser_V1.ParseBoolean(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + stlBooleanDictionary.Set(key, value); + } + } + } + + /// + /// Reparse the entire database.
+ /// 重新解析整个数据库。 + ///
+ public async Task ParseAsync_V1() + { + // 创建多个任务,并使用 LongRunning 来确保每个任务在独立线程中运行 + + // ConcurrentDictionary + Task cdStringCacheTask = Task.Factory.StartNew(() => CdString(), TaskCreationOptions.LongRunning); + Task cdIntCacheTask = Task.Factory.StartNew(() => CdInt(), TaskCreationOptions.LongRunning); + Task cdShortCacheTask = Task.Factory.StartNew(() => CdShort(), TaskCreationOptions.LongRunning); + Task cdLongCacheTask = Task.Factory.StartNew(() => CdLong(), TaskCreationOptions.LongRunning); + Task cdFloatCacheTask = Task.Factory.StartNew(() => CdFloat(), TaskCreationOptions.LongRunning); + Task cdDoubleCacheTask = Task.Factory.StartNew(() => CdDouble(), TaskCreationOptions.LongRunning); + Task cdDecimalCacheTask = Task.Factory.StartNew(() => CdDecimal(), TaskCreationOptions.LongRunning); + Task cdCharCacheTask = Task.Factory.StartNew(() => CdChar(), TaskCreationOptions.LongRunning); + Task cdBoolCacheTask = Task.Factory.StartNew(() => CdBool(), TaskCreationOptions.LongRunning); + + // SemaphoreThreadLock + Task stlStringCacheTask = Task.Factory.StartNew(() => StlString(), TaskCreationOptions.LongRunning); + Task stlIntCacheTask = Task.Factory.StartNew(() => StlInt(), TaskCreationOptions.LongRunning); + Task stlShortCacheTask = Task.Factory.StartNew(() => StlShort(), TaskCreationOptions.LongRunning); + Task stlLongCacheTask = Task.Factory.StartNew(() => StlLong(), TaskCreationOptions.LongRunning); + Task stlFloatCacheTask = Task.Factory.StartNew(() => StlFloat(), TaskCreationOptions.LongRunning); + Task stlDoubleCacheTask = Task.Factory.StartNew(() => StlDouble(), TaskCreationOptions.LongRunning); + Task stlDecimalCacheTask = Task.Factory.StartNew(() => StlDecimal(), TaskCreationOptions.LongRunning); + Task stlCharCacheTask = Task.Factory.StartNew(() => StlChar(), TaskCreationOptions.LongRunning); + Task stlBoolCacheTask = Task.Factory.StartNew(() => StlBool(), TaskCreationOptions.LongRunning); + + // 等待所有任务完成 + await Task.WhenAll(cdStringCacheTask, + cdIntCacheTask, + cdShortCacheTask, + cdLongCacheTask, + cdFloatCacheTask, + cdDoubleCacheTask, + cdDecimalCacheTask, + cdCharCacheTask, + cdBoolCacheTask, + stlStringCacheTask, + stlIntCacheTask, + stlShortCacheTask, + stlLongCacheTask, + stlFloatCacheTask, + stlDoubleCacheTask, + stlDecimalCacheTask, + stlCharCacheTask, + stlBoolCacheTask); + + // ConcurrentDictionary + async void CdString() + { + var dict = DataParser_V1.ParseString(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await cdStringDictionary.SetAsync(key, value); + } + } + async void CdShort() + { + var dict = DataParser_V1.ParseShort(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await cdShortDictionary.SetAsync(key, value); + } + } + async void CdLong() + { + var dict = DataParser_V1.ParseLong(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await cdLongDictionary.SetAsync(key, value); + } + } + async void CdInt() + { + var dict = DataParser_V1.ParseInt(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await cdIntegerDictionary.SetAsync(key, value); + } + } + async void CdFloat() + { + var dict = DataParser_V1.ParseFloat(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await cdFloatDictionary.SetAsync(key, value); + } + } + async void CdDouble() + { + var dict = DataParser_V1.ParseDouble(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await cdDoubleDictionary.SetAsync(key, value); + } + } + async void CdDecimal() + { + var dict = DataParser_V1.ParseDecimal(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await cdDecimalDictionary.SetAsync(key, value); + } + } + async void CdChar() + { + var dict = DataParser_V1.ParseChar(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await cdCharDictionary.SetAsync(key, value); + } + } + async void CdBool() + { + var dict = DataParser_V1.ParseBoolean(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await cdBooleanDictionary.SetAsync(key, value); + } + } + + // SemaphoreThreadLock + async void StlString() + { + var dict = DataParser_V1.ParseString(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await stlStringDictionary.SetAsync(key, value); + } + } + async void StlShort() + { + var dict = DataParser_V1.ParseShort(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await stlShortDictionary.SetAsync(key, value); + } + } + async void StlLong() + { + var dict = DataParser_V1.ParseLong(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await stlLongDictionary.SetAsync(key, value); + } + } + async void StlInt() + { + var dict = DataParser_V1.ParseInt(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await stlIntegerDictionary.SetAsync(key, value); + } + } + async void StlFloat() + { + var dict = DataParser_V1.ParseFloat(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await stlFloatDictionary.SetAsync(key, value); + } + } + async void StlDouble() + { + var dict = DataParser_V1.ParseDouble(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await stlDoubleDictionary.SetAsync(key, value); + } + } + async void StlDecimal() + { + var dict = DataParser_V1.ParseDecimal(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await stlDecimalDictionary.SetAsync(key, value); + } + } + async void StlChar() + { + var dict = DataParser_V1.ParseChar(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await stlCharDictionary.SetAsync(key, value); + } + } + async void StlBool() + { + var dict = DataParser_V1.ParseBoolean(_databaseContent); + + // 遍历 dict 中的每一项 + foreach (var kvp in dict) + { + var key = kvp.Key; // 获取第一个值 (key) + var value = kvp.Value; // 获取第二个值 (value) + + // 将 key-value 对存储到缓存 + await stlBooleanDictionary.SetAsync(key, value); + } + } + } + } +} diff --git a/TYLDDB/TYLDDB_PrivateField.cs b/TYLDDB/TYLDDB_PrivateField.cs new file mode 100644 index 0000000..52254b2 --- /dev/null +++ b/TYLDDB/TYLDDB_PrivateField.cs @@ -0,0 +1,35 @@ +using TYLDDB.Utils.Database; +using TYLDDB.Utils.FastCache.ConcurrentDictionary; +using TYLDDB.Utils.FastCache.SemaphoreThreadLock; + +namespace TYLDDB +{ + public partial class LDDB + { + #region 私有字段 + private string _filePath; // 存储文件路径 + private string _fileContent; // 存储文件内容 + private string _databaseContent; // 存储数据库内容 + private Database_V1 database_v1; + private Database_V2 database_v2; + 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; + #endregion + } +} diff --git a/TYLDDB/Utils/Database/V1.cs b/TYLDDB/Utils/Database/V1.cs index b33c9c4..85cb750 100644 --- a/TYLDDB/Utils/Database/V1.cs +++ b/TYLDDB/Utils/Database/V1.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; using System.Text.RegularExpressions; -using TYLDDB.Basic; +using TYLDDB.Basic.Exception; namespace TYLDDB.Utils.Database { @@ -52,7 +52,7 @@ public string GetDatabaseContent(string content, string databaseName) else { // 如果未找到匹配项,抛出自定义异常 - throw new GetDatabaseContentErrorException($"未找到数据库 '{databaseName}' 的内容。"); + throw new GetDatabaseContentErrorException($"No content found for database '{databaseName}'."); } } } diff --git a/TYLDDB/Utils/Database/V2.cs b/TYLDDB/Utils/Database/V2.cs index 071d07a..4ef461d 100644 --- a/TYLDDB/Utils/Database/V2.cs +++ b/TYLDDB/Utils/Database/V2.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; namespace TYLDDB.Utils.Database { diff --git a/TYLDDB/Utils/Reader.cs b/TYLDDB/Utils/Reader.cs index 68e9949..41eee24 100644 --- a/TYLDDB/Utils/Reader.cs +++ b/TYLDDB/Utils/Reader.cs @@ -1,5 +1,7 @@ -using System.IO; +using System; +using System.IO; using System.Text; +using TYLDDB.Basic.Exception; namespace TYLDDB.Utils { @@ -17,24 +19,66 @@ public struct Reader /// File content
文件内容
public static string ReadFile(string filePath) { - // 这里采用分块读取文件的方式,避免一次性加载大文件 - 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)) + try { - int bytesRead; - while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) + // 这里采用分块读取文件的方式,避免一次性加载大文件 + 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)) { - // 将每一块数据转换成字符串并累积到 fileContent 中 - string chunkContent = Encoding.UTF8.GetString(buffer, 0, bytesRead); - fileContent.Append(chunkContent); + 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(); + } + catch(Exception e) + { + throw new ReadException(e.Message); } + } - // 返回文件的全部内容 - return fileContent.ToString(); + /// + /// Read file.(Custom buffer)
+ /// 读取文件。(自定义缓冲区) + ///
+ /// File path
文件路径 + /// Buffer size
缓冲区大小 + /// File content
文件内容
+ public static string ReadFile(string filePath, int bufferSize) + { + try + { + // 这里采用分块读取文件的方式,避免一次性加载大文件 + 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(); + } + catch (Exception e) + { + throw new ReadException(e.Message); + } } } } diff --git a/TYLDDB/Utils/Writer.cs b/TYLDDB/Utils/Writer.cs index a2eb667..b7def69 100644 --- a/TYLDDB/Utils/Writer.cs +++ b/TYLDDB/Utils/Writer.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Text; +using TYLDDB.Basic.Exception; namespace TYLDDB.Utils { @@ -16,8 +17,12 @@ namespace TYLDDB.Utils /// 适用于在较快的硬盘中写入内容,如固态硬盘。 /// 适用于在较快的硬盘中异步写入内容,如固态硬盘。 ///
- public struct Writer + public readonly struct Writer { + private static readonly int bufferSize = 64 * 1024; // 64KB 缓冲区 + + private static int offset = 0; + /// /// Write large strings to a file synchronously.
/// 同步写入大字符串到文件。 @@ -26,14 +31,18 @@ public struct Writer /// Written content
写入的内容 public static void WriteStringToFile(string filePath, string content) { - // 使用64KB的缓冲区 - int bufferSize = 64 * 1024; // 64KB 缓冲区 - - // 使用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); + try + { + // 使用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); + } + catch(Exception ex) + { + throw new WriteStringToFileException(ex.Message); + } } /// @@ -44,14 +53,18 @@ public static void WriteStringToFile(string filePath, string content) /// Written content
写入的内容 public static async void WriteStringToFileAsync(string filePath, string content) { - // 使用64KB的缓冲区 - int bufferSize = 64 * 1024; // 64KB 缓冲区 - - // 使用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); + try + { + // 使用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); + } + catch(Exception ex) +{ + throw new WriteStringToFileException(ex.Message); + } } /// @@ -63,20 +76,25 @@ public static async void WriteStringToFileAsync(string filePath, string content) /// Block size
分块大小 public static void WriteStringToFileInChunks(string filePath, string content, int chunkSize = 64 * 1024) { + try + { + // 将字符串转换为字节数组 + byte[] contentBytes = Encoding.UTF8.GetBytes(content); - // 将字符串转换为字节数组 - byte[] contentBytes = Encoding.UTF8.GetBytes(content); - - 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; + 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; - while (offset < totalLength) + while (offset < totalLength) + { + int length = Math.Min(chunkSize, totalLength - offset); + writer.Write(Encoding.UTF8.GetString(contentBytes, offset, length)); + offset += length; + } + } + catch(Exception ex) { - int length = Math.Min(chunkSize, totalLength - offset); - writer.Write(Encoding.UTF8.GetString(contentBytes, offset, length)); - offset += length; + throw new WriteStringToFileInChunksException(ex.Message); } } @@ -89,24 +107,30 @@ public static void WriteStringToFileInChunks(string filePath, string content, in /// Block size
分块大小 public static async void WriteStringToFileInChunksAsync(string filePath, string content, int chunkSize = 64 * 1024) { - // 将字符串转换为字节数组 - byte[] contentBytes = Encoding.UTF8.GetBytes(content); + try + { + // 将字符串转换为字节数组 + byte[] contentBytes = Encoding.UTF8.GetBytes(content); - 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; + 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; - while (offset < totalLength) - { - int length = Math.Min(chunkSize, totalLength - offset); - string chunk = Encoding.UTF8.GetString(contentBytes, 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; + } + } + catch (Exception ex) + { + throw new WriteStringToFileInChunksException(ex.Message); } } }