该程序结束后会发生什么工作,计划于Task.Run()? [英] What happens to work scheduled by Task.Run() after the the program terminates?

查看:82
本文介绍了该程序结束后会发生什么工作,计划于Task.Run()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做与第三方物流和异步/等待一些测试,发现了一些,我觉得意外的:我是调度工作中使用lambda表达式和Task.Run运行,例如:

  Task.Run(()=> Console.WriteLine(尼斯计划));
 

然后我意识到,如果程序立即返回工作永远不会执行。的是,在任何.NET应用程序的预期行为(WPF,表格等)?是否有讨论这个问题的任何文档?

这意味着,Task.Run实际上是一个不走的消防和忘记的场景。

解决方案
  

这意味着,Task.Run实际上是一个不走的消防和忘记的场景。

好了,你不这样做的需要的忘了 - 你要等到它完成。所以,使用工作就是退还给您。

要做到这一点,你需要保持跟踪所有未完成的任务,你推出这种方式,然后使用类似 Task.WaitAll(任务)的非后台线程。你可能并不需要记住自己的任务 - 你只需要拥有在每个任务完成后该递减计数器,然后你只需要等待,要获得零

这是很难给出比这更具体的建议,而不更多地了解你的情况下,说实话......但这样的事情肯定会工作。

您可以很容易地封装,当然这在自己方便的方法。

I was doing some tests with the TPL and async/await and noticed something that I find unexpected: I was scheduling work to run using lambdas and Task.Run, for instance:

Task.Run(()=>Console.WriteLine("Nice program"));

And then I realized that if program immediately returns the work is never executed. Is that the expected behavior in any .NET application (WPF, Forms, etc.)? Is there any documentation that discusses this?

This means that Task.Run is actually a no-go for fire-and-forget scenarios.

解决方案

This means that Task.Run is actually a no-go for fire-and-forget scenarios.

Well, you don't want to forget - you want to wait until it's completed. So use the Task that's returned to you.

To do that, you'll need to keep track of all uncompleted tasks that you launch this way, and then use something like Task.WaitAll(tasks) in a non-background thread. You potentially don't need to remember the tasks themselves - you just need to have a counter which is decremented when each task completes, and then you just need to wait for that to get to zero.

It's hard to give more concrete advice than that without knowing more about your scenario, to be honest... but something like that would certainly work.

You can easily encapsulate this in your own convenience methods, of course.

这篇关于该程序结束后会发生什么工作,计划于Task.Run()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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