开发者

Difference between Lazy<T> and LazyInit<T>

开发者 https://www.devze.com 2023-02-19 07:19 出处:网络
I had the following line in a class that I was using. private static readonly LazyInit<TestClass> _instance = new LazyInit<TestClass>(() => new TestClass(), LazyInitMode.EnsureSingleE

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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号