Task.WaitAll和太短的任务 [英] Task.WaitAll and too short tasks

查看:85
本文介绍了Task.WaitAll和太短的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var tasks = Items.Select(i=> Task.Factory.StartNew(()=> i.DoSomething()));
Task.WaitAll(tasks.ToArray());



在上面的代码中,当DoSomething太短而在WaitAll被调用之前结束时会发生什么。 ( Items 关闭了具有不同实现的不同子类)


In the above code, What happens when DoSomething is too short that it ends before WaitAll is called. (Items are off different sub-classes with different implementations)

推荐答案

任务支持例如属性IsCompleted和一个包含TaskStatus值的Status,其中有几个可以完成,即有或没有错完成。

https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v = vs.110)的.aspx [ ^ ]



Task.WaitAll接受一系列任务并等待所有任务完成。

https://msdn.microsoft.com/en-us/library /dd270695(v=vs.110).aspx [ ^ ]



在一个非常不可能的情况下,一个Task实际上会在crating代码中的下一个语句之前旋转并返回,WaitAll的实现仍然会等到所有都完成后,在这种情况下,第一次检查完成成功,代码将从下一行继续。在你的示例代码中,'nothing'将会发生,因为你没有包含下一个语句,这与确实花费更长时间来进行比较相比,等待进入它的监视器循环
A task supports for instance the property IsCompleted and a Status containing a TaskStatus value of which several can be completed i.e. completed with or without fault.
https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx[^]

The Task.WaitAll takes an array of tasks and waits for all of them to complete.
https://msdn.microsoft.com/en-us/library/dd270695(v=vs.110).aspx[^]

In the very unlikely case that a Task will actually spin up and return before the next statement in the crating code, the implementation of WaitAll will still wait until all have completed and in this case the first check for completion succeeds and the code will simply continue from the next line. In your example code 'nothing' will happen as you did not include the next statement, which is just the same as if indeed it took marginally longer to complate than the await to enter it's monitor loop


这篇关于Task.WaitAll和太短的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆