Creating Simple Tasks

To perform a simple Task, create a new instance of the Task class, passing in a System.Action delegate that represents the workload that you want performed as a constructor argument. You can explicitly create the Action delegate so that it refers to a named method, use an anonymous function, or use a lambda function. Once you have created an instance of Task, call the Start() method, and your Task is then passed to the task scheduler, which is responsible for assigning threads to perform the work. We look at the task scheduler in detail in Chapter 4. Listing 2-2 shows the different ways of creating and starting simple tasks.

Simple Tasks, while often useful, are limited by their lack of data input and result output. The TPL provides ways for you to create Tasks with both inputs and outputs, and I'll show you all of the options available in the following sections.

Listing 2-2. Four Ways to Create Basic Tasks using System;

using System.Threading.Tasks; namespace Listing_02 { class Listing_02 {

static void Main(string[] args) {

// use an Action delegate and a named method Task task1 = new Task(new Action(printMessage));

// use a anonymous delegate Task task2 = new Task(delegate { printMessage();

// use a lambda expression and a named method Task task3 = new Task(() => printMessage());

// use a lambda expression and an anonymous method Task task4 = new Task(() => { printMessage();

task1.Start() task2.Start() task3.Start() task4.Start()

// wait for input before exiting

Console.WriteLine("Main method complete. Press enter to finish."); Console.ReadLine();

static void printMessage() {

Console.WriteLine("Hello World");

Running the code in Listing 2-2 gives the obvious result of calling the printMessage() method four times, as follows:

Main method complete. Press enter to finish.

Hello World

Hello World

Hello World

Hello World

Listing 2-1 uses the Task.Factory.StartNew() method to create and start a Task. There is little difference between the approaches shown in Listing 2-2 and the Factory.StartNew() method, but Microsoft recommends using Factory.StartNew() for simple, short-lived tasks.

■ Tip You can't Start() a Task that has already run. If you need to repeat the work performed by a Task that has completed, you must create another Task instance with the same workload.

0 0

Post a comment