如果我有这样的方法
Task<bool> LongProcessTaskAsync();
返回一个开始的任务会是更好的做法吗
return Task<bool>.Factory.StartNew(() => { ... });
或者只是return new Task<bool>(() => ...)
就个人而言,我更喜欢第一种方法,但我更愿意与其他 API 和库保持一致。
返回未开始的任务是否更合适?
最佳答案
在异步/等待方法的情况下,任务将已经启动。 AFAIK,为基于任务的版本添加的所有 BCL 方法都返回已经启动的任务。不这样做有点奇怪,因为现在常见的消费者案例是:
var foo = await GetFooAsync();
[EDIT] 根据 Stephen 指出 TAP 指南涵盖了这一点(并且他已经提供了指向指南的链接),我将引用第 4 页的相关位(在 The Task-based Asynchronous Pattern Defined -> Behavior -> Task Status 中),我在关键部分周围添加了粗体+斜体。
Task Status
The Task class provides a life cycle for asynchronous operations, and that cycle is represented by the TaskStatus enumeration. In order to support corner cases of types deriving from Task and Task as well as the separation of construction from scheduling, the Task class exposes a Start method. Tasks created by its public constructors are referred to as “cold” tasks, in that they begin their life cycle in the non-scheduled TaskStatus.Created state, and it’s not until Start is called on these instances that they progress to being scheduled. All other tasks begin their life cycle in a “hot” state, meaning that the asynchronous operations they represent have already been initiated and their TaskStatus is an enumeration value other than Created.
All tasks returned from TAP methods must be “hot.” 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 prior to returning it. Consumers of a TAP method may safely assume that the returned task is “hot,” and should not attempt to call Start on any Task returned from a TAP method. Calling Start on a “hot” task will result in an InvalidOperationException (this check is handled automatically by the Task class).
关于c# - 返回 Task<T> 的方法是否应该始终启动返回的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11706788/