ASP.NET - Multi Threading

A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complicated and time consuming operations such as database access or some intense I/O operations, then it is often helpful to set different execution paths or threads, with each thread performing a particular job.
Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increases efficiency of an application.
So far we compiled programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute multiple tasks at a time, it could be divided into smaller threads.
In .Net, the threading is handled through the 'System.Threading' namespace. Creating a variable of the System.Threading.Thread type allows you to create a new thread to start working with. It allows you to create and access individual threads in a program.
A thread is created by creating a Thread object, giving its constructor a ThreadStart reference.
ThreadStart childthreat = new ThreadStart(childthreadcall);
The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution.
Following are the various states in the life cycle of a thread:
The Unstarted State : It is the situation when the instance of the thread is created but the Start method is not called.
The Unstarted State : It is the situation when the instance of the thread is created but the Start method is not called.
The Ready State : It is the situation when the thread is ready to execute and waiting CPU cycle.
The Ready State : It is the situation when the thread is ready to execute and waiting CPU cycle.
The Not Runnable State : a thread is not runnable, when:

Sleep method has been called
Wait method has been called
Blocked by I/O operations


The Not Runnable State : a thread is not runnable, when:
Sleep method has been called
Wait method has been called
Blocked by I/O operations
The Dead State : It is the situation when the thread has completed execution or has been aborted.
The Dead State : It is the situation when the thread has completed execution or has been aborted.
The Priority property of the Thread class specifies the priority of one thread with respect to other. The .Net runtime selects the ready thread with the highest priority.
The priorities could be categorized as:
Above normal
Below normal
Highest
Lowest
Normal
Once a thread is created, its priority is set using the Priority property of the thread class.
NewThread.Priority = ThreadPriority.Highest;
The Thread class has the following important properties:
The Thread class has the following important methods:
The following example illustrates the uses of the Thread class. The page has a label control for displaying messages from the child thread. The messages from the main program are directly displayed using the Response.Write() method. Hence they appear on the top of the page.
The source file is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="threaddemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

   <head runat="server">
      <title>
         Untitled Page
      </title>
   </head>
   
   <body>
      <form id="form1" runat="server">
         <div>
            <h3>Thread Example</h3>
         </div>
         
         <asp:Label ID="lblmessage" runat="server" Text="Label">
         </asp:Label>
      </form>
   </body>
   
</html>
The code behind file is as follows:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;
using System.Threading;

namespace threaddemo
{
   public partial class _Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         ThreadStart childthreat = new ThreadStart(childthreadcall);
         Response.Write("Child Thread Started <br/>");
         Thread child = new Thread(childthreat);
         
         child.Start();
         
         Response.Write("Main sleeping  for 2 seconds.......<br/>");
         Thread.Sleep(2000);
         Response.Write("<br/>Main aborting child thread<br/>");
         
         child.Abort();
      }
      
      public void childthreadcall()
      {
         try{
            lblmessage.Text = "<br />Child thread started <br/>";
            lblmessage.Text += "Child Thread: Coiunting to 10";
            
            for( int i =0; i<10; i++)
            {
               Thread.Sleep(500);
               lblmessage.Text += "<br/> in Child thread </br>";
            }
            
            lblmessage.Text += "<br/> child thread finished";
            
         }catch(ThreadAbortException e){
         
            lblmessage.Text += "<br /> child thread - exception";
            
         }finally{
            lblmessage.Text += "<br /> child thread - unable to catch the  exception";
         }
      }
   }
}
When the page is loaded, a new thread is started with the reference of the method childthreadcall(). The main thread activities are displayed directly on the web page.
When the page is loaded, a new thread is started with the reference of the method childthreadcall(). The main thread activities are displayed directly on the web page.
The second thread runs and sends messages to the label control.
The second thread runs and sends messages to the label control.
The main thread sleeps for 2000 ms, during which the child thread executes.
The main thread sleeps for 2000 ms, during which the child thread executes.
The child thread runs till it is aborted by the main thread. It raises the ThreadAbortException and is terminated.
The child thread runs till it is aborted by the main thread. It raises the ThreadAbortException and is terminated.
Control returns to the main thread.
Control returns to the main thread.
When executed the program sends the following messages:

    51 Lectures 
     5.5 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    42 Lectures 
     18 hours 

 SHIVPRASAD KOIRALA

    57 Lectures 
     3.5 hours 

 University Code

    40 Lectures 
     2.5 hours 

 University Code

    138 Lectures 
     9 hours 

 Bhrugen Patel
 Print
 Add Notes
 Bookmark this page