Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 436
dr. evil Avatar asked Aug 30 '09 16:08

dr. evil


1 Answers

The MSDN page on the IsBackground property states:

A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.

So it would imply to me that you'd have to make your thread quite defensive to ensure that it didn't leave any connections open, databases half written etc. Anything critical would need to be in a foreground thread that would prevent the application closing until it completed.

like image 99
ChrisF Avatar answered Oct 04 '22 00:10

ChrisF