Namespace:
System.Threading.Tasks
Assembly:
System.Threading (in System.Threading.dll)
Syntax
Visual Basic (Declaration) |
---|
<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True, _ ExternalThreading := True)> _ Public Class Task _ Implements IAsyncResult, IDisposable |
C# |
---|
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)] public class Task : IAsyncResult, IDisposable |
Remarks
Task instances may be created in a variety of ways. The most common approach is by using the Task type's Factory property to retrieve a TaskFactory instance that can be used to create tasks for several purposes. For example, to create a Task that runs an action, the factory's StartNew method may be used:
Copy Code | |
---|---|
// C# var t = Task.Factory.StartNew(() => DoAction()); ' Visual Basic Dim t = Task.Factory.StartNew(Function() DoAction()) |
The Task class also provides constructors that initialize the Task but that do not schedule it for execution. For performance reasons, TaskFactory's StartNew 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 Start()()() method may then be used to schedule the task for execution at a later time.
All members of Task, except for Dispose()()(), are thread-safe and may be used from multiple threads concurrently.
For operations that return values, the Task<(Of <(TResult>)>) class should be used.
For developers implementing custom debuggers, several internal and private members of Task may be useful (these may change from release to release). The Int32 m_taskId field serves as the backing store for the 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 Int32 counter is used to retrieve the next available ID for a Task). Similarly, the Int32 m_stateFlags field stores information about the current lifecycle stage of the Task, information also accessible through the Status property. The m_action System.Object field stores a reference to the Task's delegate, and the m_stateObject System.Object 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.