Created
June 22, 2020 14:15
-
-
Save ajruckman/46a3662826cb96a78e76fae25d40903a to your computer and use it in GitHub Desktop.
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
using System; | |
namespace Infrastructure | |
{ | |
public class ThreadSafeCache<T> where T : class? | |
{ | |
private readonly object _lock = new object(); | |
private T _value = default!; | |
private bool _hasSet; | |
public bool HasValue | |
{ | |
get | |
{ | |
lock (_lock) | |
{ | |
return _value != null || _hasSet; | |
} | |
} | |
} | |
public T Get() | |
{ | |
lock (_lock) | |
{ | |
if (_value == null) | |
throw new InvalidOperationException("Call to ThreadSafeCache.Get() with unset value."); | |
return _value; | |
} | |
} | |
public T Set(T newValue, bool final = false) | |
{ | |
lock (_lock) | |
{ | |
if (final) _hasSet = true; | |
return _value = newValue; | |
} | |
} | |
public delegate T ValueGetter(); | |
public T SetIf(ValueGetter valueGetter, bool final = false) | |
{ | |
lock (_lock) | |
{ | |
if (final) _hasSet = true; | |
return _value ??= valueGetter.Invoke(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment