2

When closing an application, what is the best way to close foreground threads at the same time?

From all my research, it seems to be that the best way is to set IsBackground to true..

Is this correct or is there a better way? I'm skeptical as it doesn't seem to follow Microsofts normally descriptive method name pattern.

Sayse
  • 42,633
  • 14
  • 77
  • 146
  • 1
    If your code can arbitrarily decide that it's time for the program to shut down, and just cause all of the foreground threads to exit, that's an indication that those threads should have been background threads in the first place. – Damien_The_Unbeliever Jul 26 '13 at 15:58
  • Take a look here http://stackoverflow.com/questions/6062527/how-to-kill-thread-on-exit or http://stackoverflow.com/questions/2688923/how-to-close-all-running-threads – NoWar Jul 26 '13 at 15:59
  • @Damien_The_Unbeliever - I agree with you there, it came up through a conversation on a different question about force closing an application – Sayse Jul 26 '13 at 16:00
  • @ClarkKent - That seems to suggest I'm right.. thanks – Sayse Jul 26 '13 at 16:01
  • 1
    The best way is to *not start a thread that you cannot easily ask to stop*. If you do that then the question is easily answered: ask all the threads to stop. – Eric Lippert Jul 26 '13 at 16:08

1 Answers1

2

It will certainly work, the CLR will abort a thread like that when your main startup exits. Pretty similar to using Thread.Abort(), minus the drastic failure modes you'd normally suffer from using Abort(). It is a rude abort, there's nothing that the thread itself can do to stop it. And there will be no more code that runs afterwards that could fail due to the typical problems you'd get from Abort(), like a deadlock. Other than finalizers.

Calling it "correct" is however a bit of a stretch, there's also nothing that the thread can do to terminate cleanly. Which might be detrimental if it has externally observable behavior. Like updating a dbase, talking over a socket or writing a file. That's rudely interrupted as well, potentially leaving a confused server or a half-written file that can cause trouble later. A mitigating circumstance is that this will also happen when your program dies on an unhandled exception, you'd expect it to not cause trouble either. It depends :)

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Completely agree with this (as well as the other much appreciated comments!) A thread should be given every opportunity to close in its own due course, I suppose I was looking for the least devastating way to close a thread if required, will accept this later on today. Thanks again, Hans – Sayse Jul 26 '13 at 16:31