锁定静态方法

时间:2017-12-22 12:40:55

标签: c# asp.net multithreading c#-4.0 thread-safety

请考虑以下代码:

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

    ....

如果我想在应用程序级别创建缓存,这种方法是否需要lock来处理并发?

我想要线程安全的方法。

1 个答案:

答案 0 :(得分:6)

  

如果我想在应用程序级别创建缓存,这种方法是否需要锁定才能处理并发?

不,如果您使用线程安全集合,例如ConcurrentDictionary,否则是 - 确实如此。

相关问题