Skip to content

Instantly share code, notes, and snippets.

@in-async
Created December 8, 2022 11:02
Show Gist options
  • Save in-async/88e91175649449c8d928911a386c7880 to your computer and use it in GitHub Desktop.
Save in-async/88e91175649449c8d928911a386c7880 to your computer and use it in GitHub Desktop.
非 atomic
public static class DistributedCacheExtensions {
public static async Task<T> GetOrSetAsync<T>(this IDistributedCache cache
, string key
, Func<byte[], T> deserialize
, Func<Task<(T, byte[], DistributedCacheEntryOptions options)>> factory
, CancellationToken token = default
) {
if (cache is null) { throw new ArgumentNullException(nameof(cache)); }
if (key is null) { throw new ArgumentNullException(nameof(key)); }
if (deserialize is null) { throw new ArgumentNullException(nameof(deserialize)); }
if (factory is null) { throw new ArgumentNullException(nameof(factory)); }
byte[]? value = await cache.GetAsync(key, token).ConfigureAwait(false);
if (value is { }) {
return deserialize(value);
}
(T result, value, DistributedCacheEntryOptions options) = await factory().ConfigureAwait(false);
if (options is null) {
await cache.SetAsync(key, value, token).ConfigureAwait(false);
}
else {
await cache.SetAsync(key, value, options, token).ConfigureAwait(false);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment