1

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.

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • 1
    Create a `WeakReference`, then call `GC.Collect()` and see if it is collected or not. – Enigmativity Jun 18 '17 at 11:21
  • Have a look at [Does C# stores references to tasks from TPL [duplicate]](https://stackoverflow.com/a/23133209/8098743) and [Can .NET Task instances go out of scope during run?](https://stackoverflow.com/a/2782993/8098743). This should give you an answer. –  Jun 18 '17 at 11:29

0 Answers0