加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:39:36 所属栏目:百科 来源:网络整理
导读:如果我有一个方法 Taskbool LongProcessTaskAsync(); 返回一个开始的任务是一个更好的做法 return Taskbool.Factory.StartNew(() = { ... }); 或者刚刚返回新的Task bool(()= …) 就个人而言,我更喜欢第一种方法,但我宁愿其他API和图书馆一致. 返回一个未启
如果我有一个方法
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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读