Difference between Lazy<T> and LazyInit<T>
I had the following line in a class that I was using.
private static readonly LazyInit<TestClass> _instance = new LazyInit<TestClass>(() => new TestClass(), LazyInitMode.EnsureSingleExecution);
One day I wanted to benefit all the new things that comes with .NET 4, installed it and hell breaks loose.
My LazyInit didnt work anymore. So i replaced every occurence with Lazy<T> but what about
LazyInitMode.EnsureSingleExecution
?
I thought that would be LazyThreadSafetyM开发者_运维问答ode.ExecutionAndPublication
.
private static Lazy<LookupService> s_instance = new Lazy<LookupService>(() => new LookupService(), LazyThreadSafetyMode.ExecutionAndPublication);
Are these two declerations equivelant?
Effectively, yes. By setting LazyThreadSafetyMode.ExecutionAndPublication
, you are saying that you only want a single thread to be able to construct the Lazy<T>
, which is effectively "ensuring single execution" for the construction phase. PublicationOnly
will allow multiple threads to run the constructor, but only store one result (the first completed).
精彩评论