程序终止后,由Task.Run()安排的工作将如何处理? [英] What happens to work scheduled by Task.Run() after the program terminates?

查看:409
本文介绍了程序终止后,由Task.Run()安排的工作将如何处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用TPL和async / await进行一些测试,并发现了一些意外的发现:例如,我正在安排要使用lambda和Task.Run运行的工作,例如:

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"));

然后我意识到,如果程序立即返回,则该工作将永远不会执行。那是任何.NET应用程序(WPF,Forms等)中的预期行为吗?有没有讨论这个的文档?

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?

这意味着Task.Run实际上是一劳永逸的解决方案。

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

推荐答案


这意味着Task.Run实际上是一劳永逸的解决方案。

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

好吧,您不想忘记-您要等到完成为止。因此,请使用返回给您的 Task

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

为此,您需要跟踪所有您以这种方式启动的未完成任务,然后在非后台线程中使用 Task.WaitAll(tasks)之类的东西。您可能不需要记住任务本身-您只需要拥有一个计数器,该计数器会在每个任务完成时递减,然后您只需要等待计数器变为零即可。

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天全站免登陆