Sunday, August 14, 2011

What is the use of IsBackground property of Thread?

In any programming language that supports multi-tasking (which is supported by most of the modern languages) Threads are the most important part (tool). We use threads to run something which does not need user interaction and which runs in parallel with the normal operations by the user. In C#, a special class is provided which creates a new parallel execution block called Thread. Thread has a number of properties that helps in configuring the new thread you have created.

You might be aware of the fact that Threads actually comprises a process. So when your application runs, it allocates a new process into memory, and a few threads are created. One of such Thread is the UI Thread which runs the whole application. Each thread has a property associated with it called IsBackground which identifies whether the Thread is running in foreground or in background. A background thread will not impose restriction to the process to terminate. Hence if you create a new thread and set IsBackground of the Thread to false, that indicates that if there is only this thread available and all the Foreground threads has terminated, please terminate the process without waiting for the Background thread to complete.
In other words, the IsBackground property indicates that this thread is not important enough to keep the process running. We generally do maintenance jobs in a Background Threads. Lets see how to define a Background Thread in your application :

Thread th = new Thread(RunMe);
th.IsBackground = true;

Read more: Daily .Net Tips

Posted via email from Jasper-Net