Recently I was having some issues with a singelton class that was lazy initializing a dictionary where a second thread would try to use it before it had actually been populated. So I implemented the variable initialization through the Lazy<T>
class.
Here is my code:
private static Dictionary<string, string> GroupDefaults
{
get { return mGroupDefaults.Value; }
}
private static Lazy<Dictionary<string, string>> mGroupDefaults =
new Lazy<Dictionary<string,string>>(delegate
{
Dictionary<string, string> defaults = new Dictionary<string, string>();
foreach (KeyValuePair<string, UnitGroup> groupDef in Groups)
defaults.Add(groupDef.Key, groupDef.Value.First().Key);
return defaults;
});
This fixed the problem and now I am considering making this a regular practice of mine to use the Lazy<T>
class anywhere I do lazy initialization to avoid any possible threading issues. So basically I would like to know if this is good/common practice? Or will it be detremental to performance or something?