Say I have a WPF dialog in which I have async event handlers that await some call that takes a long time. Then the user closes the dialog (and the code disposes it) before that await has returned. I would imagine that would cause a crash. Is there a prescribed way to handle this scenario using the new async/await keywords in C# 5 with the new TaskAsync methods in .NET 4.5?
Share
async/awaitshould work fine.Each WPF window does create its own
SynchronizationContext– at least right now (this is an implementation detail). But these are just simple wrappers around the commonDispatcher.So,
TaskAwaiterwill end up capturing aSynchronizationContextfor a window that gets destroyed, but it doesn’t really matter because theDispatcheris still there.Now, what your code does is another story. e.g., if you have an
asyncevent handler in this situation, it has to be able to handle resuming on a disposed instance.Both Adam and leppie have good comments: either prevent the user from closing the dialog, or cancel the task (and ensure it is cancelled before actually closing the dialog). Another good option – if your idea is to start an operation that should outlast the dialog – is to start the
Taskand then add it to a shared collection of in-progress operations. All of these options prevent the undesirable situation of anasyncevent handler running on a disposed instance.