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 LazyThreadSafetyMode.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 theLazy<T>, which is effectively “ensuring single execution” for the construction phase.PublicationOnlywill allow multiple threads to run the constructor, but only store one result (the first completed).