1

I am wondering what is the difference between two constructor overloads of Lazy<T> class.

Lazy(Func, Boolean) - Initializes a new instance of the Lazy class. When lazy initialization occurs, the specified initialization function and initialization mode are used.

Lazy(Func, LazyThreadSafetyMode) - Initializes a new instance of the Lazy class that uses the specified initialization function and thread-safety mode.

Is the second constructor more flexible from the point of thread-safety? Which LazyThreadSafetyMode member is an analogue for Lazy<...>(..., true)?

2 Answers 2

4

From Reflector:

public Lazy(Func<T> valueFactory, bool isThreadSafe) : this(valueFactory, isThreadSafe ?LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None)
{
}

So if you pass true it will convert to LazyThreadSafetyMode.ExecutionAndPublication.

false will convert to LazyThreadSafetyMode.None

By the way, if you only pass the value factor (omitting the bool altogether), it uses LazyThreadSafetyMode.ExecutionAndPublication.

Sign up to request clarification or add additional context in comments.

2 Comments

@SriramSakthivel Oops, I meant Reflector of course. :) fixed.
0

If you pass true the object is initialized with the ExecutionAndPublication lazy mode. If you pass false the object is initialized with the None mode.

If you use an overload that does not take a boolean it is initialized with the ExecutionAndPublication mode.

2 Comments

oh, Matthew was quicker and found out the same way - I used Resharper too but would not dare to post disassembled code here :-)
I think it's ok to post it - after all, it's all freely available online here: referencesource.microsoft.com

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.