Thursday, June 4, 2009

Running Parallel Tasks

.NET 4.0 introduces a more "high level" construct than thread to write parallel program, System.Threading.Tasks.Task. Task is a unit of work which could be assigned on to a CPU core. This is a versatile and comprehensive API. You can wait/join a Task, cancel a Task, continue with another task when a task completes and more. When you need this functionality, you should try this class. Task class has a static property, Factory, of type TaskFactory. This class provides methods to create tasks from different options. The simplest way to create a task is, call the StartNew(Action act) method on Task.Factory, passing an Action delegate.

By calling ContinueWith(Action) on a task, we can specify another task which should be completed after a particular task has completed.
You can wait on a task to complete, by calling wait method on task:

You can cancel a task asynchronously, by calling Cancel() on the task:


You can cancel a task Synchronously, by calling CancelAndWait():

You can run a task synchronously, by calling RunSycnronously():

No comments:

Post a Comment