Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 76 additions & 3 deletions TYLDDB.Utils.FastCache.Test/Program.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
using TYLDDB.Utils.FastCache;
using TYLDDB.Utils.FastCache;

Check warning

Code scanning / Sonarscharp (reported by Codacy)

Add or update the header of this file. Warning test

Add or update the header of this file.

Check notice

Code scanning / Sonarscharp (reported by Codacy)

Provide a 'CLSCompliant' attribute for assembly 'srcassembly.dll'. Note test

Provide a 'CLSCompliant' attribute for assembly 'srcassembly.dll'.

Check warning

Code scanning / Sonarscharp (reported by Codacy)

Provide an 'AssemblyVersion' attribute for assembly 'srcassembly.dll'. Warning test

Provide an 'AssemblyVersion' attribute for assembly 'srcassembly.dll'.

Check notice

Code scanning / Sonarscharp (reported by Codacy)

Provide a 'ComVisible' attribute for assembly 'srcassembly.dll'. Note test

Provide a 'ComVisible' attribute for assembly 'srcassembly.dll'.
using TYLDDB.Utils.FastCache.Test;

Console.WriteLine("基于信号量的缓存读写运行");
SemaphoreSlimDefault();

Console.WriteLine();
Console.WriteLine("基于信号量的缓存读写运行");
ConcurrentDictionary();
Console.ReadLine();

// 普通线程锁的数据库读写运行
// 基于信号量的缓存读写运行
static async void SemaphoreSlimDefault()
{
var setTime = new HighPrecisionTimer();
Expand All @@ -17,7 +21,7 @@
var getAllCacheTime = new HighPrecisionTimer();
var getAllCacheAsyncTime = new HighPrecisionTimer();

var cache = new Cache();
ICache cache = new SemaphoreThreadLock();

setTime.Start();
cache.Set("TESTKEY1", "TESTVALUE1");
Expand Down Expand Up @@ -68,6 +72,75 @@
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");
Expand Down
22 changes: 10 additions & 12 deletions TYLDDB/TYLDDB.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,25 +78,23 @@
/// <param name="db">name of the database<br/>数据库名称</param>
public void LoadDatabase(string db)
{
if (_isRead == true)
switch (_isRead)

Check warning

Code scanning / Sonarscharp (reported by Codacy)

Replace this 'switch' statement with 'if' statements to increase readability. Warning

Replace this 'switch' statement with 'if' statements to increase readability.
{
_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;
}
}

/// <summary>
/// Gets the contents of the database being loaded<br/>
/// 获取正在加载的数据库内容
/// </summary>
public string GetLoadingDatabaseContent()
{
return _databaseContent;
}
public string GetLoadingDatabaseContent() => _databaseContent;

Check warning

Code scanning / Sonarscharp (reported by Codacy)

Consider making method 'GetLoadingDatabaseContent' a property. Warning

Consider making method 'GetLoadingDatabaseContent' a property.

/// <summary>
/// Read the names of all databases<br />
Expand Down
12 changes: 9 additions & 3 deletions TYLDDB/TYLDDB.csproj
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netstandard2.0;netstandard2.1;net6.0;net8.0;net9.0</TargetFrameworks>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Title>TTYPDB.NET</Title>
<Version>1.0.0-alpha.1</Version>
<Authors>QingYi-Studio</Authors>
<Version>1.0.0-alpha.2</Version>
<Authors>TYLDDB-Project</Authors>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
<PackageIcon>icon.png</PackageIcon>
Expand All @@ -17,6 +17,8 @@
<ProduceReferenceAssembly>True</ProduceReferenceAssembly>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<PackageTags>DataBase</PackageTags>
<Company>QingYi-Studio</Company>
<PackageReadmeFile>README.md</PackageReadmeFile>
</PropertyGroup>

<ItemGroup>
Expand All @@ -37,6 +39,10 @@
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<None Include="..\README.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
</ItemGroup>

<ItemGroup>
Expand Down
159 changes: 159 additions & 0 deletions TYLDDB/Utils/FastCache/ConcurrentDictionary.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
using System.Collections.Concurrent;

Check notice

Code scanning / Sonarscharp (reported by Codacy)

Provide a 'ComVisible' attribute for assembly 'srcassembly.dll'. Note

Provide a 'ComVisible' attribute for assembly 'srcassembly.dll'.

Check warning

Code scanning / Sonarscharp (reported by Codacy)

Provide an 'AssemblyVersion' attribute for assembly 'srcassembly.dll'. Warning

Provide an 'AssemblyVersion' attribute for assembly 'srcassembly.dll'.

Check warning

Code scanning / Sonarscharp (reported by Codacy)

Add or update the header of this file. Warning

Add or update the header of this file.

Check notice

Code scanning / Sonarscharp (reported by Codacy)

Provide a 'CLSCompliant' attribute for assembly 'srcassembly.dll'. Note

Provide a 'CLSCompliant' attribute for assembly 'srcassembly.dll'.
using System.Collections.Generic;
using System.Threading.Tasks;

namespace TYLDDB.Utils.FastCache
{
/// <summary>
/// Use thread locks based on concurrent dictionaries to achieve high concurrency stability.<br />
/// 使用基于信号量的线程锁来实现高并发的稳定性。
/// </summary>
public class ConcurrentDictionary : ICache
{
/// <summary>
/// Thread-safe dictionary to store cache data.<br />
/// 线程安全的字典,用于存储缓存数据。
/// </summary>
private readonly ConcurrentDictionary<string, string> _cache = new ConcurrentDictionary<string, string>();

/// <summary>
/// Synchronization method: Obtain the corresponding value by key.<br />
/// 同步方法:根据键获取对应的值。
/// </summary>
/// <param name="key">Key<br />键</param>
/// <returns>Value<br />值</returns>
public string GetByKey(string key)
{
_cache.TryGetValue(key, out var value);
return value;
}

/// <summary>
/// Asynchronous method to get the corresponding value by key.<br />
/// 异步方法:根据键获取对应的值。
/// </summary>
/// <param name="key">Key<br />键</param>
/// <returns>Value<br />值</returns>
public async Task<string> GetByKeyAsync(string key)
{
return await Task.FromResult(GetByKey(key));

Check warning

Code scanning / Sonarscharp (reported by Codacy)

Add '.ConfigureAwait(false)' to this call to allow execution to continue in any thread. Warning

Add '.ConfigureAwait(false)' to this call to allow execution to continue in any thread.
}

/// <summary>
/// Get a list of keys that correspond to a specific value.<br />
/// 获取与指定值对应的所有键的列表。
/// </summary>
/// <param name="value">Value to match<br />要匹配的值</param>
/// <returns>List of keys<br />键的列表</returns>
public List<string> GetKeysByValue(string value)

Check notice

Code scanning / Sonarscharp (reported by Codacy)

Refactor this method to use a generic collection designed for inheritance. Note

Refactor this method to use a generic collection designed for inheritance.
{
var keys = new List<string>();
foreach (var kvp in _cache)
{
if (kvp.Value == value)
{
keys.Add(kvp.Key);
}
}
return keys;
}

/// <summary>
/// Asynchronous method to get a list of keys that correspond to a specific value.<br />
/// 异步方法:获取与指定值对应的所有键的列表。
/// </summary>
/// <param name="value">Value to match<br />要匹配的值</param>
/// <returns>List of keys<br />键的列表</returns>
public async Task<List<string>> GetKeysByValueAsync(string value)
{
return await Task.FromResult(GetKeysByValue(value));

Check warning

Code scanning / Sonarscharp (reported by Codacy)

Add '.ConfigureAwait(false)' to this call to allow execution to continue in any thread. Warning

Add '.ConfigureAwait(false)' to this call to allow execution to continue in any thread.
}

/// <summary>
/// Set a cache entry for a specified key.<br />
/// 为指定键设置缓存项。
/// </summary>
/// <param name="key">Key<br />键</param>
/// <param name="value">Value<br />值</param>
/// <returns>Whether the operation is successful.<br />操作是否成功。</returns>
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;
}

/// <summary>
/// Asynchronous method to set a cache entry for a specified key.<br />
/// 异步方法:为指定键设置缓存项。
/// </summary>
/// <param name="key">Key<br />键</param>
/// <param name="value">Value<br />值</param>
/// <returns>Whether the operation is successful.<br />操作是否成功。</returns>
public async Task<bool> SetAsync(string key, string value)
{
return await Task.FromResult(Set(key, value));

Check warning

Code scanning / Sonarscharp (reported by Codacy)

Add '.ConfigureAwait(false)' to this call to allow execution to continue in any thread. Warning

Add '.ConfigureAwait(false)' to this call to allow execution to continue in any thread.
}

/// <summary>
/// Remove a cache entry by its key.<br />
/// 根据键移除缓存项。
/// </summary>
/// <param name="key">Key<br />键</param>
/// <returns>Whether the removal is successful.<br />移除操作是否成功。</returns>
public bool RemoveByKey(string key)
{
return _cache.TryRemove(key, out _);
}

/// <summary>
/// Asynchronous method to remove a cache entry by its key.<br />
/// 异步方法:根据键移除缓存项。
/// </summary>
/// <param name="key">Key<br />键</param>
/// <returns>Whether the removal is successful.<br />移除操作是否成功。</returns>
public async Task<bool> RemoveByKeyAsync(string key)
{
return await Task.FromResult(RemoveByKey(key));

Check warning

Code scanning / Sonarscharp (reported by Codacy)

Add '.ConfigureAwait(false)' to this call to allow execution to continue in any thread. Warning

Add '.ConfigureAwait(false)' to this call to allow execution to continue in any thread.
}

/// <summary>
/// Clear all cache entries.<br />
/// 清空所有缓存项。
/// </summary>
public void Clear()
{
_cache.Clear();
}

/// <summary>
/// Asynchronous method to clear all cache entries.<br />
/// 异步方法:清空所有缓存项。
/// </summary>
/// <returns>Asynchronous task for clearing.<br />清空操作的异步任务。</returns>
public async Task ClearAsync()
{
await Task.Run(() => Clear());

Check warning

Code scanning / Sonarscharp (reported by Codacy)

Add '.ConfigureAwait(false)' to this call to allow execution to continue in any thread. Warning

Add '.ConfigureAwait(false)' to this call to allow execution to continue in any thread.
}

/// <summary>
/// Get all cache entries as a dictionary.<br />
/// 获取所有缓存项,返回字典。
/// </summary>
/// <returns>All cache entries as a dictionary.<br />所有缓存项的字典。</returns>
public Dictionary<string, string> GetAllCache()

Check warning

Code scanning / Sonarscharp (reported by Codacy)

Consider making method 'GetAllCache' a property. Warning

Consider making method 'GetAllCache' a property.
{
return new Dictionary<string, string>(_cache);
}

/// <summary>
/// Asynchronous method to get all cache entries as a dictionary.<br />
/// 异步方法:获取所有缓存项,返回字典。
/// </summary>
/// <returns>All cache entries as a dictionary.<br />所有缓存项的字典。</returns>
public async Task<Dictionary<string, string>> GetAllCacheAsync()
{
return await Task.FromResult(GetAllCache());

Check warning

Code scanning / Sonarscharp (reported by Codacy)

Add '.ConfigureAwait(false)' to this call to allow execution to continue in any thread. Warning

Add '.ConfigureAwait(false)' to this call to allow execution to continue in any thread.
}
}
}
Loading
Loading