At any given time, my WPF application has a bunch of async Task
s running on background threads/synchronization contexts. At shutdown, I need to set a CancellationToken
and then wait for these tasks to complete gracefully before I can start tearing down native libraries they depend on. But some of the tasks have continuations that (need to) run on the main thread, so calling Task.WaitAll(_myTasks)
from the same thread will deadlock. What I'd like to do is something like this:
while(!AreAllTasksComplete(_myTasks))
LetContinuationsThatAreWaitingForThisContextRun();
TearDownTheNativeLibraries();
But of course LetContinuationsThatAreWaitingForThisContextRun() does not exist. Is there any way to do what I'm trying to do? Do I need a completely different approach?