1
votes

I'm new to Stack Overflow. Looked up many things here but signed up today. Just started a multi-threading course.

I'm having trouble understanding when to use foreground and background threads. I am a bit new to threading. What is the advantages and disadvantages between them? When I set the property what should I be think about?

To me it seems quite convenient to use background since it means I don't have to handle the thread during closing the application, right? My teacher told me that most of the time foreground threads are used but didn't explain as to why in a way that I understand at least.

Can I get any good examples as to when one would use foreground threads and when to use background threads?

I see that C# standard library sets threads created by the Thread class constructor to foreground by default. While ThreadPool is by default background. What is the reasoning for this? Why did they write the library this way? (I know the property can be changed, I just like to know why they are this way by default).

1
There is very little to it. It just helps the CLR to figure out what it needs to do when your program's main thread ends. It looks at the other running threads and if one of them has Background = false then it keeps your program running. Until there are none left. That's all. You use Background = true when you don't care that a thread gets rudely aborted because it doesn't do anything important that other threads may care about. Say, a worker thread that runs a dbase query to update the UI. No more UI thread => you don't care. - Hans Passant
Exactly what I wanted to be sure about. Thanks. - Sandrasa

1 Answers

0
votes

I'm not a .Net expert but here is the official documentation about background property:

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.

For the thread pool case, we can assume that thread pools only manages sub-system "activities" and other "main" (foreground) threads are living to manage higher-level (ie system) "activities". As system-level threads lives, it prevents the process to stop. While thread-pooled tasks are generally not enough important to force process living.