DEV Community

Brian Nipper
Brian Nipper

Posted on • Originally published at briannipper.com on

Example of using LazyInitializer.EnsureInitialized


When looking at making systems more efficient it's helpful to think about being lazy. A helpful tool in the .NET tool belt is the static class under the System.Threading namespace LazyInitializer. In particular this class contains a method EnsureInitialized

This method is very simple to use and provides a convenient way to ensure that an initialization is called only once based on the value of the target property already being populated.

For example, if you need to load a file as part of the setting of values in an application you can use the EnsureInitialized method.

The following is a derived example of using the class to illustrate the usage pattern.

using System; using System.Collections.Generic; namespace Example.EnsureInitialized { class Program { static void Main(string[] args) { var configurationService = new ConfigurationService(); var configInfo = configurationService.ConfigInfo(); foreach(var configItem in configInfo) { Console.WriteLine(configItem.Value); } Console.ReadKey(); } } class ConfigurationService { private Dictionary _simpleExample; public ConfigurationService() { System.Threading.LazyInitializer.EnsureInitialized(ref _simpleExample, Init); } private Dictionary Init() { // The following would be replaced with some expensive operation like reading a file from disk. return new Dictionary { {1, "Hello"}, {2, "World"} }; } public Dictionary ConfigInfo() { return _simpleExample; } } }

Discussion (0)