Lazy task execution in .NET C#

Tasks in .NET can be executed lazily, i.e. only at the time when the result is needed. This may never come in certain situations. You can build tasks that are not executed until a lazy variable is required. The lazy variable is not initialised until it is read.

You can construct a lazy task in two separate steps:

Func<string> functionBody = new Func<string>(() =>
{
	Console.WriteLine("Function initialiser starting...");
	return "Some return value from the function initialiser";
});

Lazy<Task<string>> lazyInitialiser = new Lazy<Task<string>>
	(() =>
		Task<string>.Factory.StartNew(functionBody)
	);

Here we first create a function which we then pass to the Lazy constructor. You can specify the type of object that will be lazily initialised. One of the overloaded constructors of Lazy accepts a Func of Task of T which will be the initialisation function. Task.Factory.StartNew comes in handy here as we can supply our function.

You can achieve the same initialisation in one step as follows:¨

Lazy<Task<string>> inlineLazyInitialiser = new Lazy<Task<string>>(
	() => Task<string>.Factory.StartNew(() =>
	{
		Console.WriteLine("Inline initialiser starting...");
		return "Some return value from the inline lazy initialiser.";
	}));

We read the results as follows:

Console.WriteLine("Calling function initialiser within Lazy...");
Console.WriteLine(string.Concat("Result from task: ", lazyInitialiser.Value.Result));

Console.WriteLine("Calling inline lazy initialiser...");
Console.WriteLine(string.Concat("Result from task: ", inlineLazyInitialiser.Value.Result));

View the list of posts on the Task Parallel Library here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT BEST PRACTICES WITH MICROSOFT STACK & ANGULAR

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: