如果一个实例创建的线程仍然是 运行,它会被垃圾回收吗?
Will an instance be garbage collected if a thread which was created by it is still running?
public class ServiceA
{
public ServiceA()
{
Task.Run(() =>
{
while (true) { }
});
}
}
public class Program
{
public void Main()
{
new ServiceA(); // new ServiceA without any variable referencing to it
//...
//...
//...
//...
//...
//...
//...
//...
//...
//...
//...
Console.WriteLine("Would 'new ServiceA()' still alive and won't be GC"
+ " since its task is still running?");
}
}
请考虑以上代码。我想知道 ServiceA
的实例是否会被 GC,因为它总是 "born" 一个永远不会结束的任务。但是,我根本没有提及 Task
。 (即 this.task1 = Task.Run(/.../)
)。这是否意味着即使 ServiceA
个实例将被 GC,任务仍然存在?
它产生的任务与 ServiceA 的关系为零,因此它显然不会阻止 ServiceA 被收集。重要的不是某种神秘的时间关系,而是垃圾收集器在执行时可以看到的关系。如果线程有一个包含对 ServiceA 实例的引用的变量,则可以安全地收集它,但这样的集合不在您的代码中。
public class ServiceA
{
public ServiceA()
{
Task.Run(() =>
{
while (true) { }
});
}
}
public class Program
{
public void Main()
{
new ServiceA(); // new ServiceA without any variable referencing to it
//...
//...
//...
//...
//...
//...
//...
//...
//...
//...
//...
Console.WriteLine("Would 'new ServiceA()' still alive and won't be GC"
+ " since its task is still running?");
}
}
请考虑以上代码。我想知道 ServiceA
的实例是否会被 GC,因为它总是 "born" 一个永远不会结束的任务。但是,我根本没有提及 Task
。 (即 this.task1 = Task.Run(/.../)
)。这是否意味着即使 ServiceA
个实例将被 GC,任务仍然存在?
它产生的任务与 ServiceA 的关系为零,因此它显然不会阻止 ServiceA 被收集。重要的不是某种神秘的时间关系,而是垃圾收集器在执行时可以看到的关系。如果线程有一个包含对 ServiceA 实例的引用的变量,则可以安全地收集它,但这样的集合不在您的代码中。