The difference between Lazy <T> and LazyInit <T>

I had the following line in the class that I used.

private static readonly LazyInit<TestClass> _instance = new LazyInit<TestClass>(() => new TestClass(), LazyInitMode.EnsureSingleExecution); 

One day, I wanted to benefit from all the new things that come with .NET 4, install it, and hell broke.

My LazyInit no longer worked. So I replaced every event with Lazy <T> but what about LazyInitMode.EnsureSingleExecution ?

I thought it would be LazyThreadSafetyMode.ExecutionAndPublication .

 private static Lazy<LookupService> s_instance = new Lazy<LookupService>(() => new LookupService(), LazyThreadSafetyMode.ExecutionAndPublication); 

Are these two decilerations equal?

+4
source share
1 answer

Effectively, yes. By setting LazyThreadSafetyMode.ExecutionAndPublication , you say that you want only one thread to build a Lazy<T> , which effectively "provides a one-time execution" for the construction phase. PublicationOnly will allow multiple threads to run the constructor, but only save one result (the first completed).

+6
source

Source: https://habr.com/ru/post/1344704/


All Articles