本文介绍了可.NET任务实例运行期间外出的范围有多大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有code以下块的方法(使用.NET 4和任务并行库):

If I have the following block of code in a method (using .NET 4 and the Task Parallel Library):

var task = new Task(() => DoSomethingLongRunning());
task.Start();

和该方法返回,将这项任务超出了范围和被垃圾收集,还是会运行完毕?我还没有发现有任何GCing问题,但要确保我不会自己设置了一个竞争条件与GC。

and the method returns, will that task go out of scope and be garbage collected, or will it run to completion? I haven't noticed any issues with GCing, but want to make sure I'm not setting myself up for a race condition with the GC.

推荐答案

更新:

在我回答这个问题,我发现这不是真的,任务将一直运行到结束(很久以前!) - 有一个小的,比方说,弯道情况下,如果任务可能无法完成。

After I answered this question (a long time ago!) I found out that it's not true that Tasks will always run to completion - there's a small, let's say "corner" case, where tasks may not finish.

这其中的原因是这样的:我已经回答了previously,任务基本上是线程;但他们的背景的主题。当所有前台线程结束后台线程将自动终止。所以,如果你不这样做的任务和程序结束任何东西,有一个机会的任务将无法完成。

The reason for that is this: As I have answered previously, Tasks are essentially threads; but they are background threads. Background threads are automatically aborted when all foreground threads finish. So, if you don't do anything with the task and the program ends, there's a chance the task won't complete.

您应该总是在等待任务。更多信息可以在出色答卷乔恩给我被发现。

You should always await on tasks. More information can be found on the excellent answer Jon gave me.

原文:

任务计划的线程池,这意味着他们基本上threads¹(实际上,它们封装线程)。

Task are scheduled to the ThreadPool, meaning that they are essentially threads¹ (actually, they encapsulate threads).

主题文档

有没有必要保留  引用一旦你一个Thread对象  已经开始的线程。线程  继续进行,直到该线程执行  手续齐全。

所以,没有,就没有必要保留一个引用。

So, no, there is no need to retain a reference to it.

此外,文档指出preferred的方式来创建一个任务是使用它的工厂:

Also, the documentation states that the preferred way to create a Task is to use it's factory:

您还可以使用StartNew方法  创建并且在一个启动一个任务  操作。这是preferred方式  创建和如果建立开始任务  和调度不必是  分离(...)

希望它帮助。

¹因此到文档

一个任务重presents异步  操作,并在某些方面它  类似于创建一个新的线程  或线程池工作项目,但在  更高层次的抽象。

这篇关于可.NET任务实例运行期间外出的范围有多大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 07:02