What gotchas exist with Tasks and Garbage Collection?

.net, c#, garbage-collection, task, task-parallel-library

Solution

When you have uncompleted `TaskCompletionSource`, then there are always two options:

Something might complete that TCS in the future. That means that that something holds a reference to the TCS, which means it can't get GCed.

Normal rules still apply to that something, so you might need to worry about keeping that rooted.

Nothing will ever complete that TCS. That means the TCS and its Task will likely get GCed soon, but there is no risk of work not being done (because there is no work).

Problem

When does a developer need to be concerned with the effects of garbage collection when using APIs and classes derived from the Task Parallel Library? Can .NET Task instances go out of scope during run?, would seem to give a sense of security that you do not have to worry about keeping tasks in scope. However the question seems limited to Tasks running on the ThreadPool where they are then `rooted` by the ThreadPool. However, if I understand this MSDN blog post correctly, the advice from that SO question is not be generally applicable because Tasks from `TaskCompletionSource` are not similarly `rooted`. Are direct use of `TaskCompletionSource` the only time of concern? However, when consuming an API you do not know where the Task came from. Do you then need to worry about storing references to continuations in case the provided `Task` came from a `TaskCompletionSource` or some other non-rooted source? This seems to get inconvenient and complex quickly from needing to consider whether the Task is rooted or not (are Async I/O Tasks rooted?). I am struggling to find much for information on topic but it a popular enough library I feel I should not need to be reading decompiled source code to determine if I need to worry about race-conditions with the garbage collector, so I figure I must be missing or misunderstanding something.

Original source

Related problems