c# – What to do with incomplete Tasks when closing the application?

Question:

There is a list of tasks that were launched at the start of the application and each of them will not be executed in the background in an endless loop. I keep all tasks in a list

public List<Task> BackGroundTask

When I close the position what to do with these tasks for example in the handler

FormClosing()

Looked in a debugger, the status of all tasks at the moment of window closing TaskStatus = WaitingForActivation. Maybe you need to pass the CancellationToken to all tasks and call Cancel() on the CancellationToken in FormClosing()? The infrastructure with the token is present. But would you like to know more options?

Answer:

Ideally, all tasks should be passed a CancellationToken so that they have the opportunity to "know" about the cancellation. Each task can be stopped either "softly" by checking IsCancellationRequested property of the token, or "hard" by calling the ThrowIfCancellationRequested() method.

When the application ends, call cancel on the corresponding CancellationTokenSource and await ( await ) all tasks to catch possible exceptions, and write exceptions to the logs. Please note that if some tasks end "hard", then you need to have a separate catch (OperationCanceledException e) where e.CancellationToken == source.Token to filter out such tasks (although they ended with an exception, but this is a sign of their hard end).

In practice, the answer to the question depends more on your requirements :).

Scroll to Top