ARTICLE

Priority and exception handling in Thrading

Posted by Akshay Teotia Articles | Multithreading in C# November 27, 2011
Threads are executed based on their priority levels. High priority threads always get more processor time than their counterparts.
Reader Level:

Thread Priority

The System.Threading.Thread.Priority enumeration defines the priority states of a thread that in turn determines how much processor time a thread gets to execute. Every thread has a priority in the range between ThreadPriority.Lowest to ThreadPriority.Highest. Threads are executed based on their priority levels. High priority threads always get more processor time than their counterparts. By default, each thread has priority Normal.

We need thread priority when multiple threads are simultaneously active. The System.Threading.Thread.Priority enumeration consists of :

  • Highest : A value specifying that the current thread can be scheduled before threads with any other priority.

  • AboveNormal : A value specifying that the current thread can be scheduled after threads with Highest priority and before those     with Normal priority.

  • Normal : A value specifying that the current thread can be scheduled after threads with AboveNormal priority and before those with BelowNormalpriority. Note that threads have Normal priority by default.

  • BelowNormal  A value specifying that the current thread can be scheduled after threads with Normal priority and before those with Lowest priority.

  • Lowest : A value specifying that the current thread can be scheduled after threads with any other priority.

The following syntax shows how to set the thread priority:

NewThread.priority = ThreadPriority.Highest;

ThreadPriority.Highest property specifies the new priority setting for a thread. Threads are scheduled for execution based on their priority. If we have more than one high priority threads in this case. Operating system cycles through the threads giving each high priority thread some amount of processor time. Lower priority thread do not execute as long as higher priority thread is available. If at any point it encounters a higher priority thread, then the lower priority threads are preempted and give way to the higher priority thread to execute. When there are no more threads of higher priority, the operating system then selects the next lower priority threads for execution.

Gets or sets a value indicating the scheduling priority of a thread. In the following example we have two thread the priority of one thread is set to BelowNormal. Both threads increment a variable in a while loop and run for a set time. Now we see how the  the priority of a thread changing the result of the program.

using System;
using System.Threading;
namespace threadpriority
{
class PriorityTest
 {
      bool loopSwitch;
      public PriorityTest()
            {
                loopSwitch = true;
            }
 
       public bool LoopSwitch
            {
                set { loopSwitch = value; }
            }
       public void ThreadMethod()
            {
                long threadCount = 0;
 
                while (loopSwitch)
                {
                    threadCount++;
                }
                Console.WriteLine("{0} with {1,11} priority " +
                    "has a count = {2,13}", Thread.CurrentThread.Name,
                    Thread.CurrentThread.Priority.ToString(),
                    threadCount.ToString("N0"));
            }
        }

class Akshay   
   {

      static void Main()
        {
            PriorityTest priorityTest = new PriorityTest();
            ThreadStart startDelegate = new ThreadStart(priorityTest.ThreadMethod);
            Thread threadOne = new Thread(startDelegate);
            threadOne.Name = "ThreadOne";
            Thread threadTwo = new Thread(startDelegate);
            threadTwo.Name = "ThreadTwo";
           threadTwo.Priority = ThreadPriority.BelowNormal;
            threadOne.Start();
            threadTwo.Start();
            // Allow counting for 10 seconds.
            Thread.Sleep(10000);
            priorityTest.LoopSwitch = false;
            Console.Read();
        }
    }
}

Output :

thpri.gif

Note : 

  • Operating systems are not required to honor the priority of a thread.

  • Think carefully before elevating a thread's priority it can lead to problems such as resource starvation for other threads.

Exception Handling

Exception handling is a technique to handle the exception (run time error) in our program. The exception handling is hard concept in case of threading. In multi-threading the exceptions can not be cross-thread accessed, they can only be caught from the thread which code is running on. Any try/catch/finally blocks in scope when a thread is created are of no relevance to the thread when it starts executing. Consider the following program:

using System;
using System.Threading;
namespace exception_in_thread
{
class Akshay
  {
     public static void Main()
       {
          try
           {
               new Thread(Run).Start();
           }
           catch (Exception ex)
           {
                // We'll never get here!
                Console.WriteLine("Exception!");
           }
       }
     static void Run()
      {
            throw null;
      } // Throws a NullReferenceException
    }
}

The try/catch statement in example above is effectively useless, and the newly created thread will be encumbered with an unhandled  NullReferenceException .This shows that every thread have a separate path of execution. The solution of this problem is that every thread entry methods to have their own exception handlers.

using System;
using System.Threading;
namespace exception_in_thread
{
class
akshay
 
{
    public static void Main()
      {
        
new Thread (Go).Start();
      }
       static void Go()
      {
         
try
         {
            ...
           
throw null; // The NullReferenceException will get caught below
           
...
          }
         
catch (Exception ex)
          {
            Typically log the exception, and/or signal another thread
            that we've come unstuck
           
...
          }
      }
}

Hence the conclusion is that all thread entry method require a exception handler in application to avoid the exception. As we know that An unhandled exception causes the whole application to shut down with a ugly massage.

COMMENT USING