问题
When does a Task actually start?
public void DoSomething() {
Task myTask = DoSomethingAsync();
Task.WaitAll(new[] { myTask }, 2000);
}
public async Task DoSomethingAsync() {
await SomethingElse();
}
Does it start immediately when initializing it in Task myTask = DoSomethingAsync();
or does it start when you say to wait for it in Task.WaitAll(new[] { myTask }, 2000);
?
回答1:
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.
来源:https://stackoverflow.com/questions/43089372/when-does-a-c-sharp-task-actually-start