When does a C# Task actually start?
Calling an async
method returns a hot task, a task that has already been started. So there is no actual code necessary to force it to run.
According MSDN (thanks to Stephen Cleary) the Task-based Asynchronous Pattern (TAP) pattern requires returned tasks to be hot. That means that all tasks, except those created with new Task
will be hot.
From the referenced article:
Tasks that are created by the public
Task
constructors are referred to as cold tasks... All other tasks begin their life cycle in a hot state.
Task status
The Task class provides a life cycle for asynchronous operations, and that cycle is represented by the TaskStatus enumeration. To support corner cases of types that derive from Task and Task<TResult>, and to support the separation of construction from scheduling, the Task class exposes a Start method. Tasks that are created by the public Task constructors are referred to as cold tasks, because they begin their life cycle in the non-scheduled Created state and are scheduled only when Start is called on these instances.
All other tasks begin their life cycle in a hot state, which means that the asynchronous operations they represent have already been initiated and their task status is an enumeration value other than TaskStatus.Created. All tasks that are returned from TAP methods must be activated. If a TAP method internally uses a task’s constructor to instantiate the task to be returned, the TAP method must call Start on the Task object before returning it. Consumers of a TAP method may safely assume that the returned task is active and should not try to call Start on any Task that is returned from a TAP method. Calling Start on an active task results in an InvalidOperationException exception.