2

Please consider this code:

public static class SomeClass
{
    private static List<Item> Items;

    //Constructor

    public static void AddToChache(string key, object item)
    {
        Items.Add(new Item(){ key = key , content = item, DateAdded = DateTime.Now});
    }

    public static List<Item> GetAllItems()
    {
        return Items;
    } 

    ....

If I want to create a cache in application level, does this methods need lock to handle concurrency?

I want to thread-safe methods.

Arian
  • 12,793
  • 66
  • 176
  • 300
  • 3
    Might be better idea to just use existing cache (like MemoryCache) rather than implementing your own (especially using a `List` and not even `Dictionary`). – Evk Dec 22 '17 at 12:53
  • Just to reiterate comment by [itsme86](https://stackoverflow.com/users/1141432/itsme86) from your other related [question](https://stackoverflow.com/questions/47944037/is-lock-object-deparatly-necessary-for-every-static-methods?noredirect=1) "If this is supposed to be thread-safe, you should never return the actual Items collection. Once it's returned, the collection can be modified while the caller is using it. If you must return all items, return a copy of the collection instead. And yes, that copy operation would have to be locked." – Alexei Levenkov Dec 22 '17 at 16:32

1 Answers1

6

If I want to create a cache in application level, does this methods need lock to handle concurrency?

No, if you use a thread safe collection instead, e.g. ConcurrentDictionary, otherwise yes - it does.

Yurii
  • 4,811
  • 7
  • 32
  • 41
  • Thanks but the problem is I forgot DateTime property. I have more than 2 property so in this case I can't use dictionary – Arian Dec 22 '17 at 13:57