Refact task

This commit is contained in:
2024-07-12 21:33:35 +07:00
parent 0544749a69
commit dfe92d787e
5 changed files with 120 additions and 16 deletions

View File

@@ -8,11 +8,14 @@ namespace Managing.Infrastructure.Storage
public class TaskCache : ITaskCache
{
private MemoryCache _cache { get; } = MemoryCache.Default;
private CacheItemPolicy _defaultPolicy { get; } = new CacheItemPolicy();
private CacheItemPolicy _defaultPolicy { get; } = new CacheItemPolicy()
{
SlidingExpiration = TimeSpan.FromMinutes(15),
};
public async Task<T> AddOrGetExisting<T>(string key, Func<Task<T>> valueFactory)
{
var asyncLazyValue = new AsyncLazy<T>(valueFactory);
var existingValue = (AsyncLazy<T>)_cache.AddOrGetExisting(key, asyncLazyValue, _defaultPolicy);
@@ -33,6 +36,7 @@ namespace Managing.Infrastructure.Storage
// Get the most recent value with a recursive call.
return await AddOrGetExisting(key, valueFactory);
}
return result;
}
catch (Exception)
@@ -71,7 +75,7 @@ namespace Managing.Infrastructure.Storage
public virtual List<T> GetCache<T>()
{
List<T> list = new List<T>();
foreach (var item in _cache)
{
list.Add((T)item.Value);
@@ -80,4 +84,4 @@ namespace Managing.Infrastructure.Storage
return list;
}
}
}
}