Question

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.

Was it helpful?

Solution

I think storing all the CancellationTokens in not enough in your case, you also need to store the corresponding Tasks. In your Deactivated handler, you would then cancel all the tokens and then await all the stored Tasks (catching the OperationCancelledExceptions). (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.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top