Search code examples
.netmultithreadingisbackground

Can I safely rely on IsBackground in Threads when the application terminates?


I'm running some background threads in the GUI. Currently I'm implementing a personal Thread cancellation code but there is IsBackground property in threads and according MSDN they'll cancel themselves.

I know that it's going to Thread.Abort() which is nasty but there is nothing going in this background threads that I need to keep a proper state or requires proper clean-up.

I'm trying to avoid any crashes if the user just closes down the application in the middle of a background thread. Since multi-threading scenarios are quite hard to test I'd like to get your opinion on the subject.

Basically, instead of rolling my own code shall I just set IsBackground = True and forget about the rest?


Solution

  • Thread.Abort throws an exception, so if your code is already correctly written to use finally/using, it should fail gracefully and release all resources.

    edit

    I should probably give a little more detail. First, the exception is of type ThreadAbortException. The interesting thing is that, even if you catch it and do nothing, it doesn't go away. In other words, as soon as it leaves your catch block, it continues to be thrown. This is so that the (typically bad) practice of catching Exception and swallowing it doesn't stop the thread from getting aborted. If you do actually want to stop the abort, you need to catch the exception, then call Thread.ResetAbort.