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

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...