So here's what i'm trying to do :
public static class MyClass
{
private Dictionary<string,IDisposable> dict = null;
static MyClass()
{
dict = new Dictionary<string,IDisposable>();
// i fill up the dictionary in a loop here
//
}
public static UseDictionary(string name)
{
var obj = dict[name]
obj.DoSomeAction();
}
}
static void Main(string[] args)
{
Parallel.For(0, 1000, x =>
{
// assuming 'name' does exist in the dictionary
MyClass.UseDictionary("name"); // randomly throws null reference errors
});
}
I basically want to have a single instance of this class which will initialize the dictionary only once (the IDisposable item is an expensive remote connection i'm opening and i want to open it only once )
This class will be used by different asp.net pages. So i want it to be thread safe and singleton. I'm thinking initializing the dictionary in the static constructor will make it only be called once and is thread safe, not sure why i keep getting errors. Any ideas?