Does this simple cache class need thread synchronization?

Posted by DayOne on Stack Overflow See other posts from Stack Overflow or by DayOne
Published on 2010-05-26T10:20:21Z Indexed on 2010/05/26 10:31 UTC
Read the original article Hit count: 179

Filed under:

Does this simple cache class need thread synchronization ... if I remove the lock _syncLock statement will encounter any problems? I think i can remove the locks as the references should be updated correctly right? ... BUt i'm think whar happens if client code is iterating over the GetMyDataStructure method and it get replaced?

Thanks!

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;
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#