Recently, I was asked to write a 'real-time' calculator and the output value was to be stored in Redis. For legacy reasons, it also had to be stored in the database though, only the latest value had to be kept.
As the calculator was spewing values, they were stored in a ConcurrentDictionary
. When the timer was up, I created a new instance of the ConcurrentDictionary
and used an Interlocked.Exchange
to swap the reference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class DbRepository { private ConcurrentDictionary<long,decimal> _dicWithRealTimeValues; public DbRepository() { _dicWithRealTimeValues = new ConcurrentDictionary<long, decimal>(); } public void AddValue(long id, decimal value) { _dicWithRealTimeValues[id] = value; } public ConcurrentDictionary<long, decimal> GetSnapshotAndClear() { return Interlocked.Exchange(ref _dicWithRealTimeValues, new ConcurrentDictionary<long, decimal>()); } } |