Good day.

I am engaged in self-education, and thought about the question. Can you please tell me how to properly interrupt the background thread from the main one without using any global variables, etc.? I know about CancellationToken, are there other ways?

  • Thread.Abort msdn.microsoft.com/ru-ru/library/… - nick_n_a
  • It is not recommended to use the same! - Leonard Bertone
  • one
    To die - so with music))) is the right way to "interrupt". Otherwise, create a volative flag, such as isWork, test the flag inside the stream, and if it is on, exit the stream yourself. Something like while (isWork) {working (); } - nick_n_a
  • And all other methods are reduced to Thread.Abort. CancellationToken is a synchronization method between threads, you can use volative instead, and the essence is the same - test the wait variable. - nick_n_a

2 answers 2

If it is correct, then in a stream wrapper with some convenient (for the integrity of the data being processed), check some flag of the need for an interrupt and complete it in an amicable way.

  • It seems that this is the only way. Thank you - Leonard Bertone
  • one
    @LeonardBertone This is the only correct way. Because no one, except the thread itself, should know about what it does => and how to correctly complete it. But he can "hint" about such a need. How to implement it - from the public property to kollbek or event, the essence will be the same. - free_ze
  • Just do not forget to mark such a flag as volatile , otherwise there is a chance that the stream will never end. - Raider

Another crutch is used in exceptional cases: they create a new domain in the application, run a background task in it and, if canceled, simply kill this domain. Something of type Thread.Abort, but allowed

  • When a domain is unloaded, all threads running in it should be completed. If they don’t want to be unloaded, the problems are essentially the same as with Thread.Abort without a domain. - Alexander Petrov
  • @AlexanderPetrov: Is it interesting, is thread necessarily bound to a specific AppDomain? If one domain makes a call to another, then in which thread does the code work? - VladD
  • @AlexanderPetrov Well, that's not entirely true. when unloading a domain, the release of resources will be performed by the OS, and not runtime. This is how to create a process and kill it, which is not Thread.Abort - Qutrix