1 hour ago · 10 min read2013 words · Tech · hide

In this post I look at the various thread-safety modes available for the venerable Lazy<T> type. This type has been around for a long time, but I recently saw some people (understandably) confused about the interactions between LazyThreadSafetyMode and exceptions, so this post aims to demonstrate how they work. What is Lazy<T> For? The Lazy<T> type has been around since .NET Framework 4.0 (and .NET Core 1.0). It provides is a way to describe how an object should be created, while deferring the actual creation to later. In other words, the object is lazily initialized. In one of it's simplest form, it might look like this: // You provide a function that should be invoked when the object is required. Lazy<object> lazy = new(Create); // The `Create` factory method is not invoked (and the object is not created) until // you access the `Value` property on the Lazy<T> var obj = lazy.Value; // A factory method object Create() { // This would normally do something expensive or with side…

Commenting on Bubbles has been removed. Why? If you want to talk about this post, write to the author, use the comments on their blog if it has them, or reply with a "RE:" post on your own blog. Suggestions? feedback@bubbles.town