JimBoone
JimBoone

Reputation: 554

How to gracefully close WPF application with background tasks running?

I have a WPF application that I hope can spin off two data-research background tasks on startup. These background tasks will open, parse, and close files, then update data in a SqlServer database. None of these tasks need to return anything to the display thread. These background tasks do not have to run to completion, but I need to avoid leaving a file open or Sql Server in an unexpected state. The user may close the application at any time after the tasks have started. I'm using resources from System.Threading.Tasks Namespace. For one example:

var IncorporateTask = Task.Factory.StartNew(CommentIncorporateTask);
var incorporateTaskDone = IncorporateTask.ContinueWith((antecedent) => IncorporateTaskFinalize(), TaskScheduler.FromCurrentSynchronizationContext());

Do I need to take any steps to ensure that these threads are closed off cleanly, and without delaying the user's experience of closing the application?

Upvotes: 2

Views: 2261

Answers (1)

Kent Boogaart
Kent Boogaart

Reputation: 178630

You do not need to worry about threads being terminated cleanly. You do need to worry about defining the transaction boundaries of your background work and ensuring the process does not terminate within those boundaries.

I suggest you pass a CancellationToken to the background task. When the user requests to exit the process, you should:

  1. Cancel the token source.
  2. Wait on the background task. You could do something fancier by using asynchronous continuations (eg. disable all UI and show an animation until the background task terminates)

It is then the responsibility of the background task to check the cancellation token whenever relevant and terminate early if the token is canceled, and if it won't leave you in a bad state by doing so. This essentially puts the background task in charge of when termination can occur, but allows the UI to request as early a termination as possible.

Upvotes: 2

Related Questions