Will Task.WhenAny unregister continuations on unfinished Tasks?

async-await, asynchronous, c#, mono, task-parallel-library

Solution

Yes, the continuation will be removed from all the given tasks when any one of them fires.

Problem

Consider a class which has some kind of lifetime. During this lifetime, an event may occur any number of times and the event is signaled through completion of a task (which is renewed after an event). The object may also be shut down, ending its lifetime. Shutdown is also signaled through completion of a task. It may as well live forever. Now consider some kind of asynchronous workflow modelling the lifecycle of the object: ``` //will be completed on Shutdown. Is the same object for the entire lifetime. Task shutdownTask = ... while(true) { //will be completed when the event occurs. Is different on each loop. Task eventTask = ... if (await Task.WhenAny(shutdownTask, eventTask) == eventTask) { //Event has occured ... } else { //Object has been shutdown. React and leave. ... return; } } ``` An example for eventTask could be asynchronously dequeueing an object from an async Queue. Intuitively I find nothing wrong about modelling the lifecylce of an object this way. However, The object may live forever and an unbounded number of continuations are registered on shutdownTask. Or are they? Will continuations be unregistered or will the app eventually blow up? Is there a cleaner pattern to model such a control flow?

Original source