Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a task ever be interrupted by garbage collection if there are no references to it?

Sanity-check here. Suppose I start a task but I don't await it and I don't store a reference to it. In other words, I just run:

async Task PerformLongOperation() {
    await Task.Delay(10 * 1000);
    Debug.WriteLine("All done!");
}

void DoSomething() {
    // Kick off the operation and allow it to complete when it does.
    PerformLongOperation();
}

Clearly, without keeping a reference to the Task returned by PerformLongOperation(), I have no way of knowing if and when it completes. But suppose that that's not necessary in certain instances.

Is there any danger of garbage collection noticing the task running with no references to it, and cancelling it and cleaning it up?

like image 643
Brian Rak Avatar asked May 16 '18 17:05

Brian Rak


1 Answers

No. The Task class keeps a private static collection with a reference to all currently running tasks, so even if none of your code is holding a reference to it, that will be. Additionally, tasks all hold onto references of tasks representing their continuations, so any tasks representing continuations (through any number of layers of indirection) from a running task cannot be collected either.

like image 101
Servy Avatar answered Nov 03 '22 01:11

Servy