Implement value caches

This commit is contained in:
2024-09-26 10:32:38 +02:00
parent d4ef0dc34e
commit 7d06595307
4 changed files with 73 additions and 2 deletions
@@ -0,0 +1,36 @@
using System.Extensions;
using System.Threading.Tasks;
namespace System.Cache;
public sealed class AsyncValueCache<T>(Func<Task<T>> cacheRefreshOperation, TimeSpan cacheDuration)
where T : class
{
private readonly Func<Task<T>> cacheRefreshOperation = cacheRefreshOperation.ThrowIfNull(nameof(cacheRefreshOperation));
private readonly TimeSpan cacheDuration = cacheDuration;
private T? value;
private DateTime lastCacheRefresh = DateTime.MinValue;
public async Task<T> GetValue()
{
if (DateTime.Now - this.lastCacheRefresh < this.cacheDuration &&
this.value is not null)
{
return this.value;
}
return await this.PerformCacheRefresh();
}
public async Task<T> ForceCacheRefresh()
{
return await this.PerformCacheRefresh();
}
private async Task<T> PerformCacheRefresh()
{
this.value = await this.cacheRefreshOperation();
this.lastCacheRefresh = DateTime.Now;
return this.value;
}
}
@@ -0,0 +1,35 @@
using System.Extensions;
namespace System.Cache;
public sealed class ValueCache<T>(Func<T> cacheRefreshOperation, TimeSpan cacheDuration)
where T : class
{
private readonly Func<T> cacheRefreshOperation = cacheRefreshOperation.ThrowIfNull(nameof(cacheRefreshOperation));
private readonly TimeSpan cacheDuration = cacheDuration;
private T? value;
private DateTime lastCacheRefresh = DateTime.MinValue;
public T GetValue()
{
if (DateTime.Now - this.lastCacheRefresh < this.cacheDuration &&
this.value is not null)
{
return this.value;
}
return this.PerformCacheRefresh();
}
public T ForceCacheRefresh()
{
return this.PerformCacheRefresh();
}
private T PerformCacheRefresh()
{
this.value = this.cacheRefreshOperation();
this.lastCacheRefresh = DateTime.Now;
return this.value;
}
}
@@ -7,7 +7,7 @@
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<RootNamespace>System</RootNamespace>
<Version>1.6.8</Version>
<Version>1.6.9</Version>
<Authors>Alexandru Macocian</Authors>
<RepositoryUrl>https://github.com/AlexMacocian/SystemExtensions</RepositoryUrl>
<Description>Extensions for the System namespace</Description>