Task<bool> LongProcessTaskAsync();
返回一个开始的任务是一个更好的做法
return Task<bool>.Factory.StartNew(() => { ... });
或者刚刚返回新的Task< bool>(()=> …)
就个人而言,我更喜欢第一种方法,但我宁愿其他API和图书馆一致.
返回一个未启动的任务更合适吗?
解决方法
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).