Multithreading Concept using .Net – Part III

Uses of Threads

Foreground and Background Threads

By default threads are foreground and if application is trying to close and if any foreground thread is running then application will close only after closing of all foreground threads, while background threads will automatically abort when all foreground threads will close.

Therefore, you should use foreground threads to execute tasks that you really want to complete, like flushing data from a memory buffer out to disk. And you should use background threads for tasks that are not mission-critical, like recalculating spreadsheet cells or indexing records, because this work can continue again when the application restarts, and there is no need to force the application to stay active if the user wants to terminate it.

public static class Program
            public static void Main()
                // Create a new thread (defaults to foreground)
                Thread t = new Thread(Worker);
                // Make the thread a background thread
                t.IsBackground = true;
                t.Start(); // Start the thread
                // If t is a foreground thread, the application won't die for about 10 seconds
                // If t is a background thread, the application dies immediately
                Console.WriteLine("Returning from Main");
            private static void Worker()
                Thread.Sleep(10000); // Simulate doing 10 seconds of work
                // The line below only gets displayed if this code is executed by a foreground thread
                Console.WriteLine("Returning from Worker");

Thread Scheduling and Priorities Every thread is assigned a priority level ranging from 0 (the lowest) to 31 (the highest). When the system decides which thread to assign to a CPU, it examines the priority 31 threads first and schedules them in a round-robin fashion. If a priority 31 thread is schedulable, it is assigned to a CPU. At the end of this thread’s time-slice, the system checks to see whether there is another priority 31 thread that can run; if so, it allows that thread to be assigned to a CPU. So long as priority 31 threads are schedulable, the system never assigns any thread with a priority of 0 through 30 to a CPU. This condition is called starvation, and it occurs when higher-priority threads use so much CPU time that they prevent lower-priority threads from executing. Starvation is much less likely to occur on a multiprocessor machine because a priority 31 thread and a priority 30 thread can run simultaneously on such a machine. The system always tries to keep the CPUs busy, and CPUs sit idle only if no threads are schedulable.   .Net has priority levels as Enumeration so developer need not give 1-31 as priority. There are six types of priorities: Below Normal, Normal, Above Normal, High, and Highest. Of course, Normal is the default and is therefore the most common priority by far.

static void Main(string[] args)
            sample s = new sample();
            Thread th1 = new Thread(s.Go1);
            th1.Name = "Thread1";
            th1.Priority = ThreadPriority.Lowest;
            Thread th2 = new Thread(s.Go2);
            th2.Name = "Thread2";
            th2.Priority = ThreadPriority.Highest;
            Console.WriteLine("Thread execution Over");   Console.ReadLine();
class sample
        public void Go1()
            Console.WriteLine("Running thread {0}",Thread.CurrentThread.Name);
        }   public void Go2()
            Console.WriteLine("Running thread {0}", Thread.CurrentThread.Name);

OutPut Running Thread Thread2 Running Thread Thread1   In Above Code Priority of Thread1 is lowest and Thread2 with Highest priority. CPU runs Highest Priority thread first.

Thread Pooling

Creating and destroying a thread is an expensive operation in terms of time. In addition, having lots of threads wastes memory resources and also hurts performance due to the operating system having to schedule and context switch between the runnable threads. To improve this situation, the CLR contains code to manage its own thread pool. You can think of a thread pool as being a set of threads that are available for your application’s own use. There is one thread pool per CLR; this thread pool is shared by all AppDomains controlled by that CLR. If multiple CLRs load within a single process, then each CLR has its own thread pool.

The great thing about the thread pool is that it manages the tension between having a few threads, to keep from wasting resources, and having more threads, to take advantage of multiprocessors, hyper threaded processors, and multi-core processors. And the thread pool is heuristic. If your application needs to perform many tasks and CPUs are available, the thread pool creates more threads. If your application’s workload decreases, the thread pool threads kill themselves.

I hope this post gave you good clarity on uses of threads.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Powered by

Up ↑

%d bloggers like this: