简体   繁体   English

在ASP MVC中创建线程安全的静态字典

[英]Creating a thread-safe, static Dictionary in ASP MVC

I am working on an ASP.NET MVC application which includes a static Dictionary. 我正在研究包含静态字典的ASP.NET MVC应用程序。 This is problematic because the Dictionary class is not thread-safe, which may cause trouble when it is accessed by concurrent web requests. 这是有问题的,因为Dictionary类不是线程安全的,当并发Web请求访问它时可能会引起麻烦。 I am considering wrapping the dictionary like this: 我正在考虑像这样包装字典:

public class DataDictionary
{
    private object Lock = new object();
    private int NextId = 0;
    private Dictionary<int, Data> DataLog = new Dictionary<int, Data> {};

    public int Add(Data data)
    {
        lock (Lock)
        {
            var id = NextId++;
            DataLog.Add(id, data);
            return id;
        }
    }

    public Data GetData (int id)
    {
        lock (Lock)
        {
            return DataLog[id];
        }
    }

    public void Remove(int id)
    {
        lock (Lock)
        {
            DataLog.Remove(id);
        }
    }
}

Will this allow safe access to the Dictionary by concurrent web requests? 这样是否可以通过并发Web请求安全地访问字典? If not, what can I do to facilitate similar behavior safely? 如果没有,我该怎么做才能安全地促进类似行为?

What about a ConcurrentDictionary, there's documentation on it here . 怎么样一个ConcurrentDictionary,有它的文档在这里

The first line of this documentation states: 本文档的第一行指出:

Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently. 表示可以由多个线程同时访问的键/值对的线程安全集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM