#946 – Specifying Whether Lazy Instantiated Object Should Be Thread-Safe

You can use the Lazy<T> class to declare an object that will be lazily instantiated–that is, created just before it is used.

In the example below, we indicate that the listOfAllFamousDogs object should only be created (by calling GenerateBigListOfFamousDogs) just before it is referenced.  The GenerateBigListOfFamousDogs method returns an instance of List<Dog>.

private static Lazy<List<Dog>> listOfAllFamousDogs = new Lazy<List<Dog>> (GenerateBigListOfFamousDogs);

In the Lazy<T> constructor, we specify a delegate that will be called to initialize our object.  By default, this results in a thread-safe implementation that lazily instantiates the specified object.

If we do not need thread-safety, we can pass a second parameter to the Lazy<T> constructor, with a value of false.

        // No need for thread safety
        private static Lazy<List<Dog>> listOfAllFamousDogs = new Lazy<List<Dog>> (GenerateBigListOfFamousDogs, false);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

4 Responses to #946 – Specifying Whether Lazy Instantiated Object Should Be Thread-Safe

  1. Pingback: Dew Drop – October 7, 2013 (#1,639) | Morning Dew

  2. Dirk Strauss says:

    This is awesome Sean! Thank you!

  3. Pingback: Windows 8.1 Mail Experience In The Daily Six Pack: October 8, 2013

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: