As DateTime
cannot be declared as volatile
, is this right?
private DateTime _time;
public DateTime Time
{
get
{
Thread.MemoryBarrier();
return _time;
}
set
{
_time = value;
Thread.MemoryBarrier();
}
}
That property could be accessed from different threads, so I want to ensure they get always the latest version, without use contention (lock
).
EDIT:
- I have a collection of hard-to-create items, each one has a
DateTime
property namedCreationTime
, indicating when this item was created. It's initialized toDateTime.UtcNow
. - Every time a item is accessed, that property is updated to
DateTime.UtcNow
. - There is a thread, that executes in timely fashion in a threaded timer that checks
if (DateTime.UtcNow + 1 hour) > item.CreationTime
, if true it deletes the item.
I want to ensure that when the "deletion thread" comes into the collection, all the items have their latest "last access" DateTime
on it, so I can avoid create the item again just because a cache held the value for a couple of milliseconds. :D
InterlockedExchange
solution is the way to go here. – Gownsman