Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 891
Alex Avatar asked Feb 01 '26 07:02

Alex


1 Answers

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.

like image 96
Peter Ritchie Avatar answered Feb 03 '26 20:02

Peter Ritchie