Last active
June 24, 2022 01:35
-
-
Save in-async/9d8274f6ef0011d7058f4f286b99c827 to your computer and use it in GitHub Desktop.
期限付き Lazy
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 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; | |
} |
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
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