T
T
tommy872018-02-07 16:50:32
C++ / C#
tommy87, 2018-02-07 16:50:32

C# how to create a thread safe counter cache?

It is necessary to accumulate the value by the key (i.e. accumulate +1), after reaching the value of the counter N, delete the value from the cache. Multiple threads can access the cache.
Those. the cache must be able to perform two actions in a transaction:
- read the value and increase it by 1
- read the value and delete the key
, while other threads must wait for the same operations if the key is locked, and read the new value (or the absence of a value), " dirty read" is not allowed.
Looked at memoryCache and ConcurrentDictionary, but they don't quite fit.
What means to use?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Yudakov, 2018-02-07
@AlexanderYudakov

public sealed class MyCounterCache
{
    Dictionary<string,int> Data = new Dictionary<string,int>();

    public int Действие1()
    {
        lock(Data)
        {
            // Do what you want
        }
    }

    public int Действие2()
    {
        lock(Data)
        {
            // Do what you want
        }
    }
}

Next - do it yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question