Created
December 8, 2022 11:02
-
-
Save in-async/88e91175649449c8d928911a386c7880 to your computer and use it in GitHub Desktop.
非 atomic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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