Alex
Alex

Reputation: 887

Using of Task Parallel Library in app for Windows Phone throws ThreadAbortException

I'm using TPL in my wp7 app for some background manipulations.

The app starts a task:

var task =
    Task.Factory.StartNew(
        () =>
        {
            // Some sort of operations
        });

After this the app runs UI's updates:

task.ContinueWith(
    obj =>
    {
        // UI updates
    },
    new CancelationSource.Token,
    TaskContinuationOptions.None,
    TaskScheduler.FromCurrentSynchronizationContext());

But there is a problem. If I press back button to close app, and the task isn't finished yet, app throws AggregateException with inner ThreadAbortException. As I can understand this is because a backgound thread ended incorrectly.

How can I prevent this? Maybe is there some sort of the correct way to cancel the task?

I have only one idea - catch this exception and pretend that nothing happened. Is it right?

Upvotes: 3

Views: 930

Answers (1)

Peter Ritchie
Peter Ritchie

Reputation: 35870

When you hit the back button to exit the application, the framework waits for a short amount of time before aborting all in-progress threads. It's that aborting that is causing the exception(s).

If you want to avoid the exception, you'll have to handle the BackKeyPress event on the main page (or some other way to detect back press) and cancel your Task object. This, of course, means you need to keep track of the cancellation token.

Upvotes: 1

Related Questions