If I have a code like:
public static void Main()
{
Task.Factory.StartNew(() => {
while (true)
{
DoSomethingVeryImportant();
Thread.Sleep(500);
}
}, TaskCreationOptions.LongRunning);
Console.WriteLine("Started.");
Console.ReadLine();
Console.WriteLine("Closing.");
}
Is there a chance that this task will be finalized since there are no references to it?
Will var task = Task.Factory.StartNew(...
solve the problem?
I understand that in this specific case it would be better to use local task
variable, CancellationToken
, cancel the task and wait for it to end, but now I am curious about the other thing - the behaviour of GC towards unreferenced Task
.