(I apologize if this was answered elsewhere, it looks like this will be a common problem, but it is hard to find, since terms such as "threading" and "cache" give amazing results.)
I have an expensive computation whose result is often accessed, but rarely. Thus, I cache the resulting value. Here's some C # pseudo code, which I mean:
int? _cachedResult = null;
int GetComputationResult()
{
if(_cachedResult == null)
{
_cachedResult = ;
}
return _cachedResult.Value;
}
Elsewhere in my code, I sometimes set it _cachedResultback to null because the input to the calculation has changed, and therefore the cached result is no longer valid and needs to be redistributed. (This means that I cannot use Lazy<T>, because it Lazy<T>does not support reset.)
This works great for single-threaded scenarios, but of course it is not entirely safe for threads. So my question is: what is the most efficient way to make it GetComputationResultthread safe?
Obviously, I could just put all this in a blocking block (), but I suspect there might be a better way? (Something that an atomic test would do to see if you need to recalculate the result and only block if that happens?)
Thanks a lot!