Creating and starting tasks C#. NET

To create the simplest of Tasks, you only need to have a task body, that is, a delegate or action that represents the workload you want performed in parallel. The Task in Listing has a simple body, where the workload consisted of printing a message to the console. We defined the Task body using a lambda expression, which is the form we will use most often throughout this book. Table summarizes the different ways that you can use Tasks and the listings in this section that demonstrate them.

Getting Started with Tasks

Getting Started with Tasks

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 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.

Four Ways to Create Basic Tasks

Running the code 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

This uses the Task.Factory.StartNew() method to create and start a Task. There is little difference between the approaches shown in Listing 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.

Setting Task State
You can supply the state for a Task by passing in an instance
System.Action<object> and an object representing your state as the command line arguments. Setting the Task state lets you have Tasks perform similar workloads on different data. For example, imagine that we want our four Tasks from the previous example to print out different messages to the console so that we know which technique printed which message. We create instances of Action<object> to set the message that we wanted each task to print out and use them as we create the Tasks.

Adding Task State

The example may not seem that useful until we pick one technique for creating Tasks and then use the state feature to create several at once. Listing shows how to get the same effect as in Listingbut in a much clearer and more concise manner. Now, we are able to create several Tasks, each of which has the same code statements in the body, but which operates on different state data.

Creating Several Tasks Using Task State

Notice that we explicitly cast the state data to a string so that we can call the printMessage() method in the lambda expression in Listing. The only way to pass state to a Task constructor is using Action<object>, so you must convert or cast explicitly if you need to access the members of a specific type. Running the code produces the following results:

Main method complete. Press enter to finish.

Message: Second task

Message: Fourth task

Message: First task

Message: Third task

The order in which the messages print out when you run the code may be different to the order shown in these results. The task scheduler decides how to allocate threads to perform Tasks and the order can vary.

Getting a Result
To get a result from a Task, create instances of Task<T>, where T is the type of the result that will be produced and return an instance of that type in your Task body. To read the result, you call the Result property of the Task you created. It is simple and easy to do. The above shows two Tasks that return results, one that uses state and one that doesn’t.

Getting Results from a Task

Reading the Result property waits until the Task it has been called on has completed. In Listing, this means that the second Task will not be started until the first has completed, because we call the Result property on the first Task before creating and starting the second Task.

In Listing, we are able to create and start a new Task using the static Task.Factory.StartNew()method. Task.Factory also includes the StartNew<T> method, which will create and start a Task<T> in a single step

Getting a Result with the Task Factory

Specifying Task Creation Options

Some of the constructor overloads for Task allow values from the
System.Threading.Tasks.TaskCreationOptions enumeration to be specified.

Members of the TaskCreationOptions Enumeration

Members of the TaskCreationOptions Enumeration

Identifying Tasks

The Task.CurrentId property returns a unique int that identifies the current Task. This property will return null if it is called outside of a Task body.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C#. NET Topics