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

public List<Task> BackGroundTask 

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

 FormClosing() 

I looked in the debugger, the status of all tasks at the time of closing the window TaskStatus = WaitingForActivation. May need to pass CancellationToken to all tasks and in FormClosing () call Cancel () on CancellationToken? Infrastructure with token present. But I would like to know more options?

  • CanselationToken does not have a Clouse () method. Instead, Can c elationTokenSource has a Cancel () method - Pavel Mayorov
  • 2
    First of all, you have to ask yourself what exactly you need to do in the sense of your program: wait until all tasks are done, or cut them off? - VladD
  • CancelationTokenSource is the Cancel () method - that's right, I myself did not write correctly. I think that I won't be able to wait for them there an endless cycle of polling and only not processed Exception will interrupt them. I think when you close the application, you can just pick them off. there the main block is waiting for a response on TcpIp 6 clients and on SerialPort - 6 slave devices. There is no work with the database in this layer or any other critical sections of the code. - Aldmi
  • Where are all the guys ??? - Aldmi
  • The question is still relevant - Aldmi

1 answer 1

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

When the application terminates, you cancel the corresponding CancellationTokenSource and wait ( await ) all tasks to catch possible exceptions, and write exceptions in the logs. Note that if some tasks are completed "hard", then you need to have a separate catch (OperationCanceledException e) where e.CancellationToken == source.Token to filter such tasks (although they ended with an exception, but this is a sign of "hard" completion.

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

  • @Etki corrected in vain, everything was written correctly. It's about running tasks. - andreycha
  • Here anyway the genitive is impossible. And in any case, the test question will be "what?" - in the task. - etki
  • @Etki talk about running tasksAH. Plural. - andreycha
  • oh, vtupil, I repent - etki