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# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.