c# - 返回 Task<T> 的方法是否应该始终启动返回的任务?

标签 c# task-parallel-library

如果我有这样的方法

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/

相关文章:

c# - 如何从outlook邮件中提取表格

c# - 替代具有保证交付的 Dataflow BroadcastBlock

.net - 队列任务调度程序 : How to deal with AppDomain unload?

具有队列触发的 Azure WebJob 多次触发

c# - 知道 TPL 数据流 block 是否繁忙的方法?

c# - 使用构造函数初始化 POCO 实体

c# - 为什么导航栏菜单项不显示在 twitter.bootstrap.mvc4 包示例应用程序中?

c# - 是否有更有效的方法来编写使用 DateTime 值的 IF 语句?

c# - 使用 SQL 插入日期时间(同时转换为字符串)

c# - 是否需要定义 Int 变量才能从不同线程访问?