Give the following class:
public class LockfreeThing
{
public DateTimeOffset? When { get; private set; }
public void Work(DateTimeOffset? someOffset)
{
var copy = When;
if (copy.HasValue)
{
if (copy > someOffset)
{
// Use copy safely
}
else
{
When = null;
}
}
When = someOffset;
}
}
According to this SO answer the reference assignments here are NOT thread safe due to When
backing field being a struct
.
Disregarding the possibility of var copy = When
perhaps reading off of a CPU cache and missing the most up to date value, is it possible to make such code lock-free and thread-safe?