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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/csharp/95055.html

猜你在找的C#相关文章