Add async caching extension methods
This commit is contained in:
@@ -61,4 +61,35 @@ public static class AppCacheExtensions
|
||||
|
||||
return result.TryConvertTo<T>().Result;
|
||||
}
|
||||
|
||||
public static async Task<T?> GetCacheItemAsync<T>(
|
||||
this IAppPolicyCache provider,
|
||||
string cacheKey,
|
||||
Func<Task<T?>> getCacheItemAsync,
|
||||
TimeSpan? timeout,
|
||||
bool isSliding = false,
|
||||
string[]? dependentFiles = null)
|
||||
{
|
||||
var result = provider.Get(cacheKey);
|
||||
|
||||
if (result == null)
|
||||
{
|
||||
result = await getCacheItemAsync();
|
||||
provider.Insert(cacheKey, () => result, timeout, isSliding, dependentFiles);
|
||||
}
|
||||
|
||||
return result == null ? default : result.TryConvertTo<T>().Result;
|
||||
}
|
||||
|
||||
public static async Task InsertCacheItemAsync<T>(
|
||||
this IAppPolicyCache provider,
|
||||
string cacheKey,
|
||||
Func<Task<T>> getCacheItemAsync,
|
||||
TimeSpan? timeout = null,
|
||||
bool isSliding = false,
|
||||
string[]? dependentFiles = null)
|
||||
{
|
||||
T value = await getCacheItemAsync();
|
||||
provider.Insert(cacheKey, () => value, timeout, isSliding, dependentFiles);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,4 +27,25 @@ public abstract class RuntimeAppCacheTests : AppCacheTests
|
||||
Assert.AreEqual(default(DateTime), AppCache.GetCacheItem<DateTime>("DateTimeTest"));
|
||||
Assert.AreEqual(null, AppCache.GetCacheItem<DateTime?>("DateTimeTest"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Can_Get_With_Async_Factory()
|
||||
{
|
||||
var value = await AppPolicyCache.GetCacheItemAsync("AsyncFactoryGetTest", async () => await GetValueAsync(5), TimeSpan.FromMilliseconds(100));
|
||||
Assert.AreEqual(50, value);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Can_Insert_With_Async_Factory()
|
||||
{
|
||||
await AppPolicyCache.InsertCacheItemAsync("AsyncFactoryInsertTest", async () => await GetValueAsync(10), TimeSpan.FromMilliseconds(100));
|
||||
var value = AppPolicyCache.GetCacheItem<int>("AsyncFactoryInsertTest");
|
||||
Assert.AreEqual(100, value);
|
||||
}
|
||||
|
||||
private static async Task<int> GetValueAsync(int value)
|
||||
{
|
||||
await Task.Delay(10);
|
||||
return value * 10;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user