Does this simple cache class need thread synchronization?

This simple cache class needs thread synchronization ... if I remove the lock, will the _syncLock operator run into any problems? I think I can remove the locks because the links should be edited correctly correctly? ... BUt I think that whar happens if the client code iterates using the GetMyDataStructure method and is replaced?

Edit: I replaced GetMyDataStructure with the TryGetValue style method and removed all the locks ... should this be fine?

    public bool TryGetValue(int id, out MyDataStructure myDataStructure)
    {
        return _cache.TryGetValue(id, out myDataStructure);
    }

Thank!

public sealed class Cache 
{
    private readonly object _syncLock = new object();
    private IDictionary<int, MyDataStructure> _cache;

    public Cache()
    {
        Refresh();
    }

    public void Refresh()
    {
        lock (_syncLock)
        {
            _cache = DAL.GetMyDataStructure();
        }
    }

    public IDictionary<int, MyDataStructure> **GetMyDataStructure**()
    {
        lock (_syncLock)
        {
            return _cache;
        }
    }
}
+3
source share
4 answers

Cache . , . ! , . , , - // , .

( ) - , -.


; TryGetValue , .

+1

(. 5.5 #), lock Refresh.

GetMyDataStructure, - , . .

+1

I think this would be safe, because link assignment is atomic (if there is no implicit conversion).

0
source

A lock in GetMyDataStructure does almost nothing ...

Better think about what you will do with older _cache instances that might be bound to a static or other long-lived object in your code. in fact it will be hell. Do not use this approach.

0
source

Source: https://habr.com/ru/post/1747169/


All Articles