Threading

From JholJhapata
Revision as of 05:33, 29 November 2020 by Admin (talk | contribs)

.Net supports parallel execution through multithreading. A thread is an independent execution path, able to run simultaneously with other threads. A client program starts in a single thread(the “main” thread) created by the CLR/Operating System and and we can make it a multithreaded program by creating additional threads.

   using System;
   using System.Threading;
   namespace ConsoleAppThread
   {
       class Program
       {
           static void Main()
           {
               Thread childThread = new Thread(WriteY); // Create a new thread
               childThread.Start(); // running childThread()
                                    // Simultaneously, do run on the main thread.
           for (int i = 0; i < 100; i++) Console.Write("Main Thread..");
               Console.ReadLine();
           }
           static void WriteY()
           {
               for (int i = 0; i < 100; i++) Console.Write("Child Thread..");
           }
       }
   }

The main thread creates a new thread(Child Thread) on which it runs a method that repeatedly prints "Child Thread..". Simultaneously, the main thread repeatedly prints the character "Main Thread..". Here is the output:

   Child Thread..Child Thread..Main Thread..Main Thread..Main Thread..Main Thread..Main Thread..Main Thread..Main Thread..Main Thread..Main Thread..Main Thread..Main Thread..Main Thread..Main Thread..Main Thread..Main Thread..Main Thread...............Child Thread..Child Thread..Child Thread..Child Thread..Child Thread..Child Thread........Main Thread..Main Thread..Main Thread..Main Thread.........Child Thread..Child Thread..Child Thread..Child Thread..Child Thread..Child Thread............

Properties of Thread

Sr.No. Property Description
1 ApartmentState Gets or sets the apartment state of this thread.
2 CurrentContext Gets the current context in which the thread is executing.
3 CurrentCulture Gets or sets the culture for the current thread.
4 CurrentPrinciple Gets or sets the thread's current principal (for role-based security).
5 CurrentThread Gets the currently running thread.
6 CurrentUICulture Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run-time.
7 ExecutionContext Gets an ExecutionContext object that contains information about the various contexts of the current thread.
8 IsAlive Gets a value indicating the execution status of the current thread.
9 IsBackground Gets or sets a value indicating whether or not a thread is a background thread.
10 IsThreadPoolThread Gets a value indicating whether or not a thread belongs to the managed thread pool.
11 ManagedThreadId Gets a unique identifier for the current managed thread.
12 Name Gets or sets the name of the thread.
13 Priority Gets or sets a value indicating the scheduling priority of a thread.
14 ThreadState Gets a value containing the states of the current thread.