Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

ASP.NET multithreaded


May 13, 2021 ASP.NET


Table of contents


Multithreading

A thread is defined as the execution path of a program. E ach thread defines a unique traffic control. I f your application involves complex and time-consuming operations, such as database access or some intense I/O operation, it is often useful to set different execution paths or threads, each thread performing a specific job.

Threads are lightweight processes. A common example of using threads is the implementation of parallel programming for modern operating systems. U sing threads saves CPU cycles and improves application efficiency.

So far we've compiled a program that runs on a thread as a single process, that is, an instance of the application running. H owever, such an application can only perform one job at a time. L et it perform multiple tasks at the same time, and you can divide it into smaller threads.

At .Net, threads are processed through the namespace 'System.Threading'. V ariables of the system.threading.thread type created allow you to create a new thread to start working. It allows you to create and access separate threads on a separate thread.

Create a thread

A thread is created by a thread object and gives a reference to the open thread of its constructor.

    ThreadStart childthreat = new ThreadStart(childthreadcall);

Thread lifecycle

The life cycle of a thread begins when an object of the system.threading.thread class is created and ends when the thread is terminated or executed.

Here are the various states in the life cycle of a thread:

  • Pending state: The case in which an instance of the thread is created but the startup method has not yet been called.
  • Ready state: When the thread is ready to execute and waiting for a CPU cycle.
  • Non-operational: There are several possibilities when a thread cannot be run:
    • The method of current sleep is called
    • The waiting method is called
    • Blocked by I/O operations
  • Dead state: The condition in which the thread has completed execution or has been aborted.

Thread priority

Priority properties in the Thread class primarily specify a thread's priority relative to other threads. The .NET runtime selects the ready thread with the highest priority. P riority can be divided into:

  • above normal
  • below normal
  • Highest
  • Minimum
  • Normal

Once a thread is created, the system prioritizes it using the thread class's priority setting system.

    NewThread.Priority = ThreadPriority.Highest;

The properties and methods of the thread

Thread classes have the following important characteristics:

Property Describe
CurrentContext Gets the contents of the thread that is currently executing.
CurrentCulture Gets or sets the environment of the current thread.
CurrentPrinciple Gets or sets the current process's principles about role-based security mechanisms.
CurrentThread Gets the thread that is currently running.
CurrentUICulture Get or set up the currently running process's resource manager to find the current environment for a particular resource.
ExecutionContext Gets the ExecutionContext object that contains contextual information about the current thread.
IsAlive Gets a value that indicates the execution state of the current thread.
IsBackground A value is obtained or set in the background to indicate whether the thread is a background thread.
IsThreadPoolThread Gets a value that indicates whether the thread belongs to the managed thread pool.
ManagedThreadId Gets the current unique identifier for the managed thread.
Name Gets or sets the name of the thread.
Priority Gets or sets a value that represents the scheduling priority of a thread.
ThreadState Gets a value that contains the state of the current thread.

Thread classes have the following important methods:

Method Describe
Abort Calling a ThreadAbortException to start the process of terminating a thread, calling this method usually terminates the thread.
AllocateDataSlot All threads are assigned an unnamed data slot. For better performance, use a domain labeled threadStaticAttribute.
AllocateNamedDataSlot The named data slot is assigned to all threads. For better performance, you are using a domain labeled threadStaticAttribute.
BeginCriticalRegion Notify the host execution that it is about to enter the code area, where the impact of thread aborts or unprocessed exceptions can jeopardize the application area of other tasks.
BeginThreadAffinity Notify the colocage code that it is going to execute, depending on the identity description of the current physical operating system thread.
EndCriticalRegion Notify the host that execution is about to enter the code area, where thread aborts or unprocessed exceptions affect only the current task.
EndThreadAffinity Notifying the host that managed code is complete depends on the identification description of the current physical operating system thread.
FreeNamedDataSlot To eliminate the association of names with slots for all threads in the process, for better performance, a domain labeled threadStaticAttribute is used.
GetData The current domain of the current thread retrieves values from slots specified by the current thread. For better performance, you are using a domain labeled threadStaticAttribute.
GetDomain Returns the thread currently executing in the current domain.
GetDomainID Returns a unique application domain identifier.
GetNamedDataSlot Find the named data slot. For better performance, you are using a domain labeled threadStaticAttribute.
Interrupt Interrupts a thread in the WaitSleepJoin thread state.
Join Block the calling thread until one of the threads terminates, while continuing with the standard COM and SendMessage. The method has different overload forms.
MemoryBarrier Synchronized memory access is as follows: Accelerators that handle the current thread cannot call MemoryBarrier with memory access before calling memory access to perform this way to reorder instructions.
ResetAbort Cancel the abort request for the current thread.
SetData Sets the thread in which the data is currently running on the specified time slot, the thread's current domain. For better performance, the application area is the domain of the ThreadStaticAttribute property.
Start Start a thread.
Sleep Pause the thread for a period of time.
SpinWait The number of iterations that make the thread wait for the parameter definition.
VolatileRead() Read the value of the field. T he most recent value is written by any processor on the computer, regardless of the processor or the number of states that the processor caches. The method has different overload forms.
VolatileWrite() Write a value to the field immediately that is visible to all processors on the computer. The method has different overload forms.
Yield Another thread that enables the calling thread to execute can run on the current processor, and the operating system chooses to steer to the county

Example

The following example illustrates the use of thread classes. T he page has a control tab that shows messages coming from subthreads. M essages from the main program are displayed directly using the response.write(50) method, so they appear at 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 background code 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";
            }
          }
       }
    }

Observe the following:

  • When the page is loaded, a new thread starts with childthreadcall() as a reference. T he activity of the main thread appears directly on the page.
  • The second thread runs and sends the message to the control label.
  • The main thread hibernates for 2000 milliseconds while the child thread executes.
  • The child thread continues to run until it is aborted by the main thread, and then it throws the ThreadAbortException exception and terminates it.
  • Control returns to the main thread.
  • When executed, the program sends the following information:

ASP.NET multithreaded