PROWAREtech

articles » current » dot-net » lazy-load-data

.NET: Lazy Load Data

How to lazy load data using the C# programming language.

Lazy loading is a design pattern commonly used to defer initialization of an object until the point at which it is needed. This can improve performance, reduce system overhead, and ensure efficient use of resources. Lazy loading is especially useful when dealing with large objects or resources whose creation is computationally expensive.

Using Lazy<T> Class

The .NET Framework provides a convenient way to implement lazy loading through the Lazy<T> class. Here’s how to use it:

  1. Define the Lazy<T> Instance: Define a Lazy<T> variable where T is the type of object to lazily initialize.

  2. Initialization Logic: Pass a delegate to the constructor of Lazy<T> that contains the initialization logic of the object.

  3. Access the Value: Access the object through the Value property of the Lazy<T> instance. The instance will be created at this point if it hasn't been already.


using System;

class BigSlowResource
{
    public BigSlowResource()
    {
        Console.WriteLine("BigSlowResource created!");
    }
    public void Operate()
    {
        Console.WriteLine("Operating!");
    }
}

class Program
{
    static void Main()
    {
        Lazy<BigSlowResource> lazyResource = new Lazy<BigSlowResource>(() => new BigSlowResource());

        Console.WriteLine("Lazy object created, resource not initialized yet.");
        
        // The BigSlowResource object is created when accessing the Value property.
        lazyResource.Value.Operate();
    }
}

Or:


// NOTE: incompatible with .NET Core 3.1
using System;
using System.Collections.Generic;
using System.Text.Json;

class Program
{
	private static readonly Lazy<List<string>?> LazyListOfStrings = new(LoadListFromJson);
	private static List<string>? LoadListFromJson()
	{
		string json = "[\"1\",\"2\"]";
		return JsonSerializer.Deserialize<List<string>>(json);
	}

	static void Main()
	{
		foreach(var s in LazyListOfStrings.Value)
			Console.WriteLine(s);
	}
}

Custom Lazy Loading

If wanting more control over the initialization logic or if not working in an environment where Lazy<T> is available, implement lazy loading manually:


class BigData
{
    private BigResource _resource;
    public BigResourceResource
    {
        get
        {
            if (_resource == null)
            {
                _resource = new BigResource();
            }
            return _resource;
        }
    }
}

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE