1

I need to store and update List in MemoryCache. Every transaction hitting my WEB.API will add a record to this List, and every 1 min the list will be dumped into database and removed from cache.

My issue is concurrency and avoiding dirty reads/writes. I also need to write to this list very quickly so my transaction is not delayed.

// get list in cache
List<MyObj> stat = cache.Get<List<MyObj>>(key);

if (stat == null)
  stat = new List<MyObj>() { new MyObj() { SomeKey = SomeVal } };
else
  stat.Add(new MyObj() { SomeKey = SomeVal });

// by this time another thread could modify the cached object, so my current object is not good anymore
cache.Set<List<MyObj>>(key, stat);
Dmitriy
  • 129
  • 1
  • 8
  • 3
    Maybe [`BlockingCollection`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.blockingcollection-1?view=netframework-4.8) would suit better your needs? Another options is [`ConcurrentQueue`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentqueue-1?view=netframework-4.8) – abatishchev Jul 11 '19 at 01:35
  • You'll need a `lock` around **all** accesses of that `List` if you continue to use `List` since `List` is not thread-safe. – mjwills Jul 11 '19 at 01:36
  • I agree with @abatishchev. `BlockingCollection` or `ConcurrentQueue` is likely what you want. – mjwills Jul 11 '19 at 01:37
  • Look at this post: https://stackoverflow.com/q/1362995/559144 – Davide Piras Jul 11 '19 at 01:39
  • @mjwills even though `MemoryCache` is thread-safe, this particular usage of it is not. Multiple threads could get `stat == null` for the same `key` in the time it takes to create a `new List`. – Patrick Roberts Jul 11 '19 at 01:44
  • That is correct @PatrickRoberts. The OP should thus likely not use a `MemoryCache` at all - and just use a `static` `ConcurrentQueue`. – mjwills Jul 11 '19 at 01:46
  • 2
    Thanks All. I have decided to implement a Singleton of BlockingCollection instead of using MemoryCache. This is working for me. – Dmitriy Jul 11 '19 at 16:38
  • Please post a sketch or some PoC of what you've ended up with (and accept as an answer), this will help others! – abatishchev Jul 12 '19 at 01:52

0 Answers0