Creating and Starting Tasks

The Task Parallel Library (TPL) lives in the System.Threading.Tasks namespace, and we’ll assume this namespace to be imported in the code examples that follow. To create a new task, first think about the work you want to run and whether it returns a value. If so, your goal is to create a Task<TResult> instance. Here, the generic parameter is substituted for the return type of the operation. If no data has to be returned, a nongeneric Task object can be created.

Using the Task Constructor

One way to create a new task is by using the Task<TResult> or Task constructor, where you pass in a delegate to the operation that has to be carried out. (Obviously, anonymous method expressions or lambda expressions can be used for ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.