Lazy initialization of an object means that object creation is deferred until the object is actually used by your program. If you have a parallel task that you want to execute only when the value returned from the task is actually needed, you can combine lazy task execution with the Task.Factory.StartNew method.
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
//
// .NET 4.5 Parallel Extensions Cookbook
// Chapter 1: Lazy Task Execution
//
// Lazy initialization of an object means that object creation is deferred until
// the object is actually used by your program. If you have a parallel task that
// you want to execute only when the value returned from the task is actually
// needed, you can combine lazy task execution with the Task.Factory.StartNew
// method.
//
// In this recipe, we will return to our, by now familiar WordCount solution, to
// show you how to execute a parallel task and compute a word count for our
// book, only when we display the result to the console.
//
// https://www.packtpub.com/application-development/net-45-parallel-extensions-cookbook
//
namespace WordCount5
{
class Program
{
static void Main()
{
var lazyCount = new Lazy<Task<int>>(() => Task<int>.Factory.StartNew(() => // Task declaration and body go here
{
Console.WriteLine("Executing the task.");
char[] delimiters = { ' ', ',', '.', ';', ':', '-', '_', '/', '\u000A' };
const string userAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)";
const string uri = "http://www.gutenberg.org/files/2009/2009.txt";
var client = new WebClient();
client.Headers.Add("user-agent", userAgent);
var words = client.DownloadString(uri);
var wordArray = words.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
return wordArray.Count();
}
));
Console.WriteLine("Calling the lazy variable");
Console.WriteLine("Origin of species word count: {0}", lazyCount.Value.Result);
Console.WriteLine("Press <Enter> to exit.");
Console.ReadLine();
}
}
}