Introduction to Multi Threading

Discussion in 'ASP.NET' started by MinalS, Aug 26, 2015.

  1. The threads provides user with an independent control for the flow of code. User can minimize the CPU resources and provide good use of the available components. A single thread is associated with a single process in an ASP.NET application.

    If user needs to perform multiple tasks simultaneously, the concept of multi threading is used. In multithreading, a single thread is divided into number of small threads. The System.Threading namespace consist of the required classes. User can create a thread and use it in the program.

    Thread life cycle



    The object of System.Threading class marks the start of the thread life cycle. Once the thread is terminated, the execution of it is completed.

    The different states present in the thread life cycle are as mentioned below:
    1. Unstarted state: The instance of the thread is created. User does not call the start method. It is an empty object. There are no system resources allocated to it.
    2. Ready state: The thread is ready for execution and is waiting for the CPU cycle. The Start() method is used for making the thread runnable.
    3. Not Runnable state: A thread is present in the not runnable state if there are following three conditions:
      • a) Wait: The Wait( ) method is used for placing the thread in a wait condition for a specific time
      • b) Sleep: the Sleep() method is used to keep the thread in sleeping mode
      • c) Blocked: The thread can be blocked by an input / output operation. Once it is blocked, it enters in not runnable state.
    4. Dead state: A thread is present in the dead state when the method inside the thread has completed its operation. The Abort() method is used for ending the state. Once there are no references for the thread, the garbage collector removes it.

    Thread properties and methods



    Thread class is associated with some properties and methods used for its execution. They are listed below:

    Properties of thread
    1. CurrentContext: The current context in which the thread is executing is accessed.
    2. CurrentPrincipal: The current principal of the thread is accessed or assigned.
    3. CurrentThread: The current running thread is retrieved
    4. IsAlive: The execution status of the thread is accessed
    5. IsBackground: The value stating the thread contains a background thread.
    6. Name: The name of the thread is accessed or assigned.
    7. Priority: A value stating the scheduling priority of the thread is accessed.
    8. ThreadState: A value containing the current thread state.
    9. ExecutionContext: It contains information about the thread contexts.
    Methods of thread
    1. AllocateDataSlot: An unnamed data slot is allocated to the thread.
    2. Abort: A ThreadAbortException is raised in the thread on which the object is invoked.
    3. BeginCriticalRegion: When the execution is about to enter the region where the thread abort is affected or an unhandled exception can destroy other tasks in the application domain.
    4. EndCriticalRegion: The host is about to enter the region where the thread abort and unhandled exception are preserved for the current task.
    5. GetData: The value from the particular slot is retrieved in the current thread domain.
    6. FreeNamedDataSlot: The relation with the name and a slot is removed.
    7. GetDomain: The current domain in which the thread is executing is retrieved
    8. Interrupt: The thread is interrupted when it is in WaitSleepJoin state
    9. GetNamedDataSlot: The named data slot is accessed. The ThreadStaticAttribute is used
    10. ResetAbort: The request is aborted or cancelled.
    11. Start: It marks the start of the thread
    12. Yield: The system selects the thread to be yield. The calling thread is used to yield the execution to another thread.
    13. VolatileRead(): The value is read from the field. It is the latest value written by the processor.
    14. VolatileWrite(): Writes a value to a field immediately such that it is visible for all the processors.

    Thread Priority



    The Thread class has a priority property used for stating the priority of a thread with relation to another. The thread can be divided into five types as lowest, highest, above normal, below normal, and normal.

    The priority of the thread class can be set using the Priority property of the thread class.

    Code:
    
    NewThread.Priority = ThreadPriority.Lowest;
    
    

    Example demonstrating the use of multi threading in ASP.NET


    1. Create an ASP.NET web application in Visual studio
    2. Add the following code in the source view of the application.

      Code:
      
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
          <title></title>
      </head>
      
      <body>
          <form id="form1" runat="server">
          <div>
          <asp:Label ID="lbl1" runat="server" Text="Show" />
          </div>
          </form>
      </body>
      </html>
      
      
    3. Add the following code in the code behind file.

      Code:
      
      using System;
      using System.Collection.Generic;
      using System.Linq;
      using System.Web;
      using System.Web.UI;
      using System.Web.UI.Controls;
      using System.Threading;
      
      namespace WebApplication1
      {
          public partial class WebForm1: System.Web.UI.Page
          {
              protected void Page_Load(object sender, EventArgs e)
              {
                  ThreadStart ts = new ThreadStart(child1);
                  Response.Write("Start of child thread<br/>");
                  Thread child = new Thread(ts);
                  
                  child.Start();
                  
                  Response.Write("<br/>Sleeping for 5 seconds<br/>");
                  Thread.Sleep(5000);
                  Response.Write("Aborting the thread);
                  child.Abort();
      
              }
      
          public void child1()
          {
              try
              {
                  lbl1.Text="Child thread started<br/>";
                  for ( int i=0; i < 5; i++)
                  {
                      Thread.Sleep(1000);
                      lbl1.Text="child";
                  }
                  lbl1.Text = "<br/>Child thread completed<br/>";
              }
              catch(ThreadAbortException e)
              {
                  lbl1.Text = "<br/>child thread exception";
              }
              finally
              {
                  lbl1.Text="<br/>child thread cannot catch exception<br/>";
              }
          }
      
    4. Once the code is compiled and executed, the following output is generated.

      [​IMG]
     
    Last edited by a moderator: Jan 21, 2017

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice