Lazy task execution in .NET C#
April 2, 2014 Leave a comment
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.