I need a global data in my application. My application uses several threads to access and add items to my global variable. The global variable is a ConcurrentDictionary
I choose to ensure data is added to the variable. What do you think about my approach?
public class GlobalData
{
private static volatile GlobalData instance;
private volatile ConcurrentDictionary<string, object> _data = new ConcurrentDictionary<string, object>();
private static object syncRoot = new Object();
public static GlobalData Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new GlobalData();
}
}
return instance;
}
}
public void Add(string id, object obj)
{
_data.TryAdd(id, obj);
}
public object Get(string id)
{
object value;
_data.TryGetValue(id, out value);
return value;
}
}
Add
andGet
methods, which means, dollars to dimes, you have a race condition. \$\endgroup\$