24 - MultiThreading in ASP.NET

24.1 Thread Cycle

A thread is a basic unit to which the operating system allocates the processor time. It is an independent execution within the program. User can perform multiple tasks at a same time using threads in a program. A single threaded application can perform only one task at a time.

User has to wait for task to complete before another task is started. Multithreaded process executes one or more task at one time.

The life cycle of a thread starts when an object of the System.Threading.Thread class is created. The life cycle of the thread ends when the task is completed. There are various states in the life cycle of the thread. The states are as mentioned below:

1) The Unstarted state

2) The Runnable state

3) The Not Runnable state

4) The Dead state

1) The Unstarted state:

When the user creates an instance of a Thread class, the thread enters the unstarted state. A new thread is an empty object of the Thread class. No system resources are allocated to it. User need to invoke the Start() method to start the thread in an application.

2) The Runnable state:

The thread remains in the unstarted state till the program calls the Start() method of the Thread class. The Start() method places the thread in the runnable state. The state is also known as ready or started state. The new thread and other threads present in the system can be executed at the same time.

A single processor cannot execute more than one thread in an application. Hence, it maintains a thread queue. When the thread is started it is lined up in the processor time and waits to be executed. Hence, the state of the thread is to be runnable and not running.

3) The Not Runnable state:

A thread is said to be in not runnable state if:

a) Sleeping: A thread is put in the sleeping mode by calling the Sleep() method

b) Waiting: A thread can be made to wait for some specified condition to be satisfied by calling the Wait() method.

c) Blocked: A thread can be blocked by an I/O operation. When the thread is blocked, it enters the not runnable state.

4) The Dead state: A running thread enters the dead state when the thread methods are complete. This state is called the terminated state. The thread enters the dead state by calling the Abort() method of the Thread class. When the thread is in the dead state and there are no references to the thread object, the garbage collector removes the thread object from the memory.

24.2 Thread Priority

Thread Priority is the property used to specify the priority of one thread with respect to the priority of other thread. Execution of multiple threads is scheduled on a single processor in a specified order. The priority of the thread is as follows:

  • Above Normal
  • Below Normal
  • Highest
  • Lowest
  • Normal

A thread with higher priority runs before the threads with lower priority. If the thread with higher priority is encountered, the current thread is pushed back and the higher priority thread is executed.

User can set the priority of the thread using the Priority property of the Thread class. The snippet that sets the priority of the thread is as shown below:

     NewThread.Priority=ThreadPriority.Highest;

The ThreadPriority.Highest property specifies the priority setting of the thread. If there are multiple threads with the same priority available in the system, the scheduler gives each thread a fixed time slice in which they execute.

24.3 Thread Properties and Methods

Some of the properties of the Thread class in ASP.NET are as mentioned below:

Properties

Description

ApartmentState

It gets or sets the apartment state of the thread

CurrentContext

It gets the current context in which the thread is executing

CurrentCulture

It gets or sets the culture of the current thread

CurrentPrincipal

It gets or sets the threads current principal

CurrentThread

It gets the currently running thread

CurrentUICulture

It gets or sets the current culture used by the Resource Manager to lookup culture specific at run time

ExecutionContext

It gets an ExecutionContext object that contains information about the various contents of the current thread

IsAlive

It gets a value indicating the execution status of the current thread

IsBackground

It gets or sets a value indicating whether a thread is a background thread

IsThreadPoolThread

It gets a value indicating whether a thread belongs to the managed pool or not

ManagedThreadID

It gets a unique identifier for the current managed thread

Name

It gets or sets the name of the thread

Priority

It gets or sets the value indicating the scheduling priority of the thread

ThreadState

It gets a value containing the states of the current thread

Some of the methods of the Thread class in ASP.NET are as mentioned below:

Methods

Description

Abort

It raises a ThreadAbortExecption in the thread on which it is invoked to begin the processing of terminating the thread

AllocateDataSlot

It allocates the unnamed data slot on all the threads

AllocateNamedDataSlot

It allocates the named data slot on all the threads

BeginCriticalRegion

It notifies the host the execution is to enter a region of code

BeginThreadAffinity

It notifies a host that managed code is about to execute instructions depending on the identity of the physical operating system thread

DisableComObjectEagerCleanup

It turns off the automatic cleanup of runtime callable wrappers for the current thread

EndCriticalRegion

It notifies the host that execution is about to enter the region of code in which the thread aborts

Equals(Object)

It determines whether the specified object is equal to the current object

GetCompressedStack

It returns a compressedstack object that is used to capture the stack for the current thread

GetDomain

It returns the current domain in which the current thread is running

GetData

It retrieves the value from the specified slot of the current thread

GetHashCode

It returns the hash code of the current thread

GetType

It gets the type of the current instance

Interrupt

It interrupts a thread that is in WaitSleepJoin thread state

ResetAbort

It cancels an abort requested for the current thread

Resume

It resumes the thread that has been suspended

SetData

It sets the data in the specified slot on the running thread

Start

It changes the current instance of the thread

Suspend

It either suspends the thread or if the thread is already suspended, it has no effect

ToString

It returns a string that represents the current object

ViolateRead()

It reads the value of the field. It the latest value written by any processor in the computer

ViolateWrite()

It writes the value in the field. The value is visible to the processors in the computer

Yield

It causes the calling thread to yield execution to another thread that is ready to run on the current processor

24.4 Example of MultiThreading

The code snippet to demonstrate the concept of multithreading is as shown below:

protected void Page_Load(object sender, EventArgs e)
{
  ThreadStart ts=mew ThreadStart(childcall);
  Response.Write(“Start of child thread<br/>”);
  Thread child1 = new Thread(ts);
  child1.Start();
  Thread.Sleep(1000);
  Response.Write(“Thread is aborting<br/>”);
  child1.Abort();
}
public void ChildCall()
{
  try
  {
   lbl1.Text=”Child Thread”;
  }
  catch(ThreadAbortException e)
  {
    lbl1.Text=Child thread is aborted<br/>”;
   }
   finally
   {
    lbl1.Text=”Exception were not cached by the child thread<br/>”;
   }
}

The output is as shown below:

Like us on Facebook