锁定静态方法

Ari*_*ian 2 c# asp.net multithreading thread-safety c#-4.0

请考虑以下代码:

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

    ....
Run Code Online (Sandbox Code Playgroud)

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

我想要线程安全的方法.

Yur*_*rii 6

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

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