Skip to content

Instantly share code, notes, and snippets.

@in-async
Last active June 24, 2022 01:35
Show Gist options
  • Save in-async/9d8274f6ef0011d7058f4f286b99c827 to your computer and use it in GitHub Desktop.
Save in-async/9d8274f6ef0011d7058f4f286b99c827 to your computer and use it in GitHub Desktop.
期限付き Lazy
public class TtlLazy<T> {
private readonly Func<T> _factory;
private readonly TimeSpan _ttl;
private T _value = default!;
private bool _initialized;
private object? _lock;
public TtlLazy(Func<T> factory, TimeSpan ttl) {
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
_ttl = ttl;
}
public T Value => LazyInitializer.EnsureInitialized(ref _value, ref _initialized, ref _lock, () => {
Task.Delay(_ttl).ContinueWith(_ => _initialized = false);
return _factory();
});
public bool IsValueCreated => _initialized;
public TimeSpan Ttl => _ttl;
}
async Task Main() {
TtlLazy<int> cache = new(() => {
return Random.Shared.Next();
}, TimeSpan.FromSeconds(0.1));
for (int i = 0; i < 100; i++) {
await Task.Delay(10).ConfigureAwait(false);
(cache.Value + "@" + Thread.CurrentThread.ManagedThreadId).Dump();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment