System.Threading.Tasks.Task Class

Represents an asynchronous operation.

See Also: Task Members

Syntax

[System.Diagnostics.DebuggerDisplay("Id = {Id}, Status = {Status}")]
[System.Diagnostics.DebuggerTypeProxy(typeof(System.Threading.Tasks.TaskDebuggerView))]
public class Task : IAsyncResult, IDisposable

Remarks

System.Threading.Tasks.Task instances may be created in a variety of ways. The most common approach is by using the task’s Task.Factory property to retrieve a System.Threading.Tasks.TaskFactory instance that can be used to create tasks for several purposes. For example, to create a System.Threading.Tasks.Task that runs an action, the factory's TaskFactory.StartNew(Action) method may be used:

Example

// C#
var t = Task.Factory.StartNew(() => DoAction());

' Visual Basic
 Dim t = Task.Factory.StartNew(Function() DoAction())

For more complete examples, see Task Parallelism (Task Parallel Library).

The System.Threading.Tasks.Task class also provides constructors that initialize the task but that do not schedule it for execution. For performance reasons, the task factory’s TaskFactory.StartNew(Action) method should be the preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation and scheduling must be separated, the constructors may be used, and the task's Task.Start method may then be used to schedule the task for execution at a later time.

For operations that return values, the System.Threading.Tasks.Task`1 class should be used.

For Debugger Developers

For developers implementing custom debuggers, several internal and private members of task may be useful (these may change from release to release). The m_taskId field serves as the backing store for the Task.Id property, however accessing this field directly from a debugger may be more efficient than accessing the same value through the property's getter method (the s_taskIdCounter counter is used to retrieve the next available ID for a task). Similarly, the m_stateFlags field stores information about the current lifecycle stage of the task, information also accessible through the Task.Status property. The m_action field stores a reference to the task's delegate, and the m_stateObject field stores the async state passed to the task by the developer. Finally, for debuggers that parse stack frames, the InternalWait method serves a potential marker for when a task is entering a wait operation.

Requirements

Namespace: System.Threading.Tasks
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 4.0.0.0