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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With