When using cooperative threads, if a thread is killed, the Thread will experience a ThreadEndException which bubbles up.
Also, I believe (but am not sure) that this exception will only be triggered at a natural yield point (e.g. a loop boundary, a call to sleep, or yield).
How does this work when a Preemptive thread is killed?
It appears that both Cooperative and Preemptive threads die in a similar fashion:
they die at a yield point (a loop boundary, sleep, or Yield call)
they both raise the ThreadEndException
There also appears to be some differences - I’m noticing that they don’t end in exactly the same way:
Preemptive
: Preemptive.49
: Preemptive.50
: Preemptive.60
: Preemptive.Sleep(100) begin
: Main Thread: Sleeping 523 done
: Main Thread: Killing Thread 1
: Preemptive.Sleep(100) finish
: Preemptive.Looping
: Preemptive.ThreadEndException
Cooperative
: Cooperative.88
: Cooperative.89
: Cooperative.90
: Cooperative.Sleep(100) begin
: Main Thread: Sleeping 498 done
: Main Thread: Killing Thread 1
: Cooperative.ThreadEndException
The difference being that the Coperative thread seems to die during Sleep(), but the Preemptive thread dies after waking up from Sleep() and then looping. Not sure if this is important.
This was important, so we’ve made it more consistent. Thread.Stop has always been a marker rather than an immediate stop; threads generally can’t be stopped unless you forcefully quit your app or wait for them to finish. It marks the thread for termination and cleans it up at an appropriate stopping point—usually during a sleep or a designated code point, as long as #pragma DisableBackgroundTasks isn’t enabled.