【发布时间】:2020-06-10 09:30:05
【问题描述】:
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,因为它总是“诞生”一个永远不会结束的任务。但是,我根本没有提及Task。 (即this.task1 = Task.Run(/.../))。这是否意味着即使ServiceA instance 被GC,Task 仍然存在?
【问题讨论】:
标签: c# multithreading reference garbage-collection task