[英]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? 如果没有,我该怎么做才能安全地促进类似行为?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.