Reputation: 924
In C# Threading, by default the new thread is a foreground thread.
But what is the use case of a background thread?
Also, on what does the main thread run -> on foreground or background thread?
Upvotes: 3
Views: 877
Reputation: 5147
According to MSDN, the main difference between foreground and background threads is:
Background threads are identical to foreground threads with one exception: a background thread does not keep the managed execution environment running. Once all foreground threads have been stopped in a managed process (where the .exe file is a managed assembly), the system stops all background threads and shuts down.
So, the use case for background threads are, tasks that should not prevent your process from terminating.
If you use a thread to monitor an activity, such as a socket connection, set its IsBackground property to true so that the thread does not prevent your process from terminating.
Considering the difference, UI thread should be foreground so that it keeps the process running until UI shuts down. If it was a background thread, the process stopped running as soon as no other foreground thread was running.
Edit:
Since you can signal the foreground threads when process is supposed to terminate, I don't see any special use case that cannot be implemented using foreground threads only. Since those thread may need to be informed about termination to free resources or perform an action, manually signaling them (rather than relying on the fact that they will be terminated because there are background) could be a better choice. But making them background would be a "Just in case" thing, that if for some reason they doesn't get signaled, they do not prevent process from terminating.
Upvotes: 3