Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Thread as background or not

I need an explanation regarding some advice I got on this site. I'm doing a newsletter sending app, and I have my mail sent in a seperate thread so the process doesn't slow down the whole web site. A couple of people advised me to set the threads IsBackground property to true. I did this, but was also courious about what this does, so I googled a bit. As it turns out, setting the IsBackground property to true indicates that "it's okay if the process shuts down while this thread is still running.". Or as microsoft puts it "Any remaining background threads are stopped and do not complete."

I don't know if I got this the wrong way but, wouldn't it be better to leave the IsBackground property to false, so that the spawned thread can complete its work regarding the main thread?

like image 384
Andrej Avatar asked Jan 02 '11 14:01

Andrej


1 Answers

If you set "IsBackground=true", you are marking the thread as nonessential -- so if you want your background job to complete even if the site goes down, I think your intuition is correct, leave it as "IsBackground=false".

This is not foolproof; the spawned thread is still a child of the main thread, so depending on how the site goes down, it can still bring down the entire process. If you really want to be sure that your job can run to completion no matter what happens to the site itself, you should think about extracting it into its own process, such as a WCF service.

like image 196
Guy Starbuck Avatar answered Nov 04 '22 23:11

Guy Starbuck