Background and Foreground Threads

by Sumant 4. May 2007 21:53
In a multi-threaded application, it becomes very important to decide whether a thread will be a foreground thread or a background thread, specially if it is an unattended process, otherwise the program may continue to run even when it is not required.

Difference between the two is that a foreground thread runs until it is complete and does not allow the application or program to terminate before its termination. On the contrast, a background thread is immediately terminated whenever the application is terminated or all foreground threads belonging to the application are terminated.

In .NET we set a thread as a background thread or as a foreground thread by setting the property 'Thread.IsBackground' to true, for background, or false to indicate a foreground thread.

For example I have an applicaton that keeps a watch on my mailbox and alerts me whenever I receive a mail. For this purpose when the application starts, it starts a thread which keeps on polling to my mail server at a regular interval and checks for new mail. When I shut down this application, I would also want this thread to stop polling to the mail server. If this thread has been set as a background thread, it will be stopped automatically once I shut down the application. But, if this thread has been set as a foreground thread, then the application needs to have some logic in the method, which is running on this thread, to terminate when the application is requested to quit.
Share   

Tags: ,

.NET

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

© 2008 Sumant Dubey

About this blog

Absolutely technical! The posts are about concepts, tricks, articles and links on technical subjects / problems which are not very obvious to understand / resolve. Purpose is to have this as the first-aid in the time of need.

RecentComments

Disclaimer

The opinions expressed on this website are my own personal opinions and do not represent my employer's view in anyway.