Skip to content

Instantly share code, notes, and snippets.

@ajruckman
Created June 22, 2020 14:15
Show Gist options
  • Save ajruckman/46a3662826cb96a78e76fae25d40903a to your computer and use it in GitHub Desktop.
Save ajruckman/46a3662826cb96a78e76fae25d40903a to your computer and use it in GitHub Desktop.
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