I want to create a ConcurrentDictionary
to store some data in my project, and want to keep it during all my app's lifetime,so it can be access by different thread to get the cached data.
I must make it's initialization thread-safe, I don’t want it to be created twice when some thread access it at the same time.
I know that the static field be initialized when it be accessed first time.So I define the ConcurrentDictionary
like this:
public class CacheData
{
public readonly static ConcurrentDictionary<string, string> ConcurrentDic = new ConcurrentDictionary<string, string>();
}
As far as i know, it's a singleton, and it's thread-safe, so what confuses me most now is I cannot find any reason to use any other solution to create a singleton such as a Lazy<ConcurrentDictionary<string, string>>
like:
public class CacheData
{
private static Lazy<ConcurrentDictionary<string, string>> _concurrentDic = new Lazy<ConcurrentDictionary<string, string>>(() =>
{
return new ConcurrentDictionary<string, string>();
});
public static ConcurrentDictionary<string, string> ConcurrentDic
{
get
{
return _concurrentDic.Value;
}
}
}
If Lazy<T>
can be completely replaced by static field here, when will Lazy<T>
be used?
Looking forward to your answer