Creating a task
Tasks are an abstraction in the .NET framework to represent asynchronous units of work. In some ways, a task resembles the creation of a classic .NET thread, but provides a higher level of abstraction,which makes your code easier to write and read.
We will look at the three basic ways to create and run a new task.
- The Parallel.Invoke() method: This method provides an easy way to run any number of concurrent statements
- The Task.Start() method: This method starts a task and schedules it for execution with TaskScheduler
- The Task.Factory.StartNew() method: This method creates and starts a task using Task.Factory
 
In this recipe, we will create a new task using each of these three methods. To give our tasks something to do, we will be using WebClient to read the text of three classic books. We will then split the words of each book into a string array, and display a count of the words in each book.
How to do it…
Ok, let's start building a Console application that demonstrates the various ways to create a parallel task.
- Launch Visual Studio 2012.
- Start a new project using the C# Console Application project template, and assign SimpleTasks as the Solution name as shown in the following screenshot: 
 
- Add the following using statements at the top of your Program class:
 
 TipDownloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visithttp://www.packtpub.com/support and register to have the files e-mailed directly to you. 
 
 
- First, let's create a task using Parallel.Invoke. Add the following code to the Main method of the Program class:
 
 
- Next, let's start task using the Start method of the Task object. Add the following code to the Main method of the Program class just below the code for the previous step:
 
 
- Finally, let's create task using Task.Factory.StartNew. Add the following code to the Main method of the Program class:
 
 
- In Visual Studio 2012, press F5 to run the project. You should see output similar to the following screenshot. Note that the exact order of the text you see may vary as tasks run asynchronously: