Skip to content

Instantly share code, notes, and snippets.

@briannipper
Last active March 14, 2024 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briannipper/ac2778ccd0d15b4ab217083331419ae7 to your computer and use it in GitHub Desktop.
Save briannipper/ac2778ccd0d15b4ab217083331419ae7 to your computer and use it in GitHub Desktop.
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<long, string> _simpleExample;
public ConfigurationService()
{
System.Threading.LazyInitializer.EnsureInitialized(ref _simpleExample, Init);
}
private Dictionary<long, string> Init()
{
// The following would be replaced with some expensive operation like reading a file from disk.
return new Dictionary<long, string>
{
{1, "Hello"},
{2, "World"}
};
}
public Dictionary<long, string> ConfigInfo()
{
return _simpleExample;
}
}
}
@igitur
Copy link

igitur commented Mar 8, 2024

But how is this different to just having

public ConfigurationService()
{
    _simpleExample = Init();
}

@briannipper
Copy link
Author

@igitur thanks for the question, sorry for the delay in following up as I was under the weather. To provide you the best response I can provide a link to the post where I explained the usage of this feature. https://www.briannipper.com/2018/09/example-of-using-lazyinitializerensurei.html

Perhaps you've already read it and are still not seeing the benefit, so in an effort to try and help explain the usage I'll use a specific use case.

If you had a class that, when initialized read values from a file on disk or a database and for the lifetime of that class you didn't want those values to change you could use the LazyInitializer.EnsureInitialized method to ensure the values were present, but you didn't have to read the external source multiple times.

To see this in action you can create an operation that reads a file and logs the activity of reading the file and then call the class multiple times and see the different behavior.

I hope this helps explain the usage of this feature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment