Search content within the blog

Sunday, April 10, 2011

Foreground or Background Thread

Types of Threads
Basically, there are two types of threads which fall into:

* Foreground Thread
* Background Thread

# Foreground threads have the ability to prevent the current application from terminating. The CLR will not shut down an application (which is to say, unload the hosting AppDomain) until all foreground threads have ended.

# Background threads (sometimes called daemon threads) are viewed by the CLR as expendable paths of execution that can be ignored at any point in time (even if they are currently laboring over some unit of work). Thus, if all foreground threads have terminated, any and all background threads are automatically killed when the application domain unloads.

It is important to note that foreground and background threads are not synonymous with primary and worker threads. By default, every thread you create via the Thread.Start() method is automatically a foreground thread. Again, this means that the AppDomain will not unload until all threads of execution have completed their units of work. In most cases, this is exactly the behavior you require.

Example:
Create a windows application with two buttons.Foreground and background threads....
add the following code for them

private void button1_Click(object sender, EventArgs e)
{
// Creates a background thread
ThreadStart threadStart = new ThreadStart(TenSecondsMethod);
Thread backgroundThread = new Thread(threadStart);
backgroundThread.IsBackground = true;
backgroundThread.Start();

MessageBox.Show("A method of 25 seconds delay is invoked!" + Environment.NewLine + "Now try closing the application and check Task Manager > Processes.");
}

private void TenSecondsMethod()
{
// Method of 25 seconds delay
Thread.Sleep(25000);
}

private void button2_Click(object sender, EventArgs e)
{
// Creates a foreground thread
ThreadStart threadStart = new ThreadStart(TenSecondsMethod);
Thread foregroundThread = new Thread(threadStart);
foregroundThread.IsBackground = false;
foregroundThread.Start();

MessageBox.Show("A method of 25 seconds delay is invoked!" + Environment.NewLine + "Now try closing the application and check Task Manager > Processes.");
}

After clicking each button, you can try closing the application.

From the windows task manager we can see the application would not be listed in the case of Background thread created.

From the windows task manager we can see the application would be still running in the case of Foreground thread created.

The following image shows the snapshot of task manager just after closing the application after invoking a foreground thread.


No comments:

Post a Comment