I think storing all the CancellationToken
s in not enough in your case, you also need to store the corresponding Task
s. In your Deactivated
handler, you would then cancel all the tokens and then await
all the stored Task
s (catching the OperationCancelledException
s). (I'm not sure how exactly does Deactivated
work with async
, you might need something to let the system know that you haven't actually finished deactivating yet.)
Race condition when cancelling tasks during app deactivation
-
09-03-2022 - |
Вопрос
I'm trying to use Task-based asynchronous pattern in my Windows Phone 8 app. Idea is that all long-running operations have reference to a cancellation token, and there's one place in app where all those tokens are stored. When app receives Deactivated
event, it iterates through all the tokens and cancels them.
The problem is that the thread with long-running operation is not scheduled to run when app deactivates, and this means if I'm trying to use CancellationToken.ThrowIfCancellationRequested();
in that thread, it's only called when app resumes, not when app deactivates. And of course this is not what I want. If I'm doing a simple trick like token.Register(() => Thread.Sleep(1000));
, i.e. pausing thread which calls to cancellation for a moment, then second thread has a chance to run, and everything is cancelled like a charm. However, this is a dirty hack and I don't want to use it in my app.
The question is how to make sure app is not exiting while operation cancellation is finished? I assume that sign of cooperative cancellation is OperationCancelledException thrown, but how to wait for it, especially if I only have a reference to CancellationTokenSource, but not to the Task object? Is there some other way to know about that?
Much thanks in advance!
P.S. If you need more code to help me, just ask.
Решение