微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如果返回任务的方法总是启动返回的任务?

如果我有一个方法
Task<bool> LongProcesstaskAsync();

返回一个开始的任务是一个更好的做法

return Task<bool>.Factory.StartNew(() => { ... });

或者刚刚返回新的Task< bool>(()=> …)

就个人而言,我更喜欢第一种方法,但我宁愿其他API和图书馆一致.

返回一个未启动的任务更合适吗?

解决方法

在异步/等待方法的情况下,任务将已经启动. AFAIK,为基于任务的版本添加的所有BCL方法都返回已启动的任务.这是不可思议的,因为现在普遍的消费者情况是:
var foo = await GetFooAsync();

[编辑]基于Stephen指出,TAP指南涵盖了这一点(他已经包含了指南的链接),我将从第4页(在基于任务的异步模式定义 – > ;行为 – >任务状态),我已经添加了关键部分的粗体斜体.

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).

原文地址:https://www.jb51.cc/csharp/95055.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐