c# - 锁定静态方法

标签 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来处理并发?

我想要线程安全的方法。

最佳答案

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

不,如果你改用线程安全的集合,例如ConcurrentDictionary ,否则是 - 它确实如此。

关于c# - 锁定静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47941742/

相关文章:

c# - 无法在 dotnet core 2.1 中注册日志记录

c# - 从其他用户控件加载用户控件 (ascx)

java - 为什么线程不会无限期地进入等待状态?

Java基本线程池带锁的实现.ReentrantLock

c# - Application.Run(Form) 与 Form.Show()?

c# - 如何在 C# 中为 RavenDB 正确创建 Map/Reduce 索引

c# - 将文件写入任何计算机上的项目文件夹

asp.net - 部署 ASP.NET 应用程序时出现解析器错误

c# - Windows 10 通用应用入门

c# - 由于类型不匹配,无法完成日期时间转换