articles

Multi-threading in C#

Anupam Mishra5262 22-Dec-2015
Introduction:

Thread is a light-weight process. In Computer Science, a thread is a smallest sequenced program instructions that can be managed independently by a thread scheduler, which is typically a part of operating system(Wikipedia). A thread is an independent execution path and able to run simultaneously with other threads.

For most common example of multi –threading is if you open your browser for downloading a file and you also open word document for editing content. As this scenario resources are same for the both applications in operating system but behind this it is working on thread that’s called multi-thread.

By multiple threads executing in sequence. It is provide parallel processing of thread.  

Multi-threading can occur in a “real” sense, in that a multi-processor box may have more than one processor executing instructions for a particular process at a time, or it may be effectively ”simulated”

Thread in C#:

To use multi-threading in c# we have to use the Threading namespace which is included in System. The System. Threading namespace includes everything we need for multi-threading.

There are main two ways to using multi-threading in c#. For first way starting your own threads with ThreadStart delegates, and using the ThreadPool class either directly (using ThreadPool.QueueUserWorkItem) or indirectly using asynchronous methods (such as Stream.BeginRead, or calling BeginInvoke on any delegate).

Starting and Stopping Threads:

For most confusion is that when you are create an instance of thread that is not for starting a thread. To start the execution of a new thread, use the Start method, as shown as follows.

Firstly creating thread t1 using ThreadStart delegate.
Thread t1 = newThread(newThreadStart());
// For starting the thread
              t1.Start();

To stop the execution of a thread, using the Abort method, as shown as follows.

t1.Abort();

Thread Methods:

 

The following are most common methods are using to control individual thread:

1.   Sleep() :Pauses a thread for a specified time(In milliseconds).

2.   Suspend():Pauses a thread when it reaches a safe point.

3.   Resume():Restarts a suspended thread.

4.   Join():Causes the current thread to wait for another thread to finish. If used with a time-out value, this method returns True if the thread finishes in the allocated time. 

Thread Priorities:

According to priority we have set the time slice of thread to give the processor for execution of thread. Every thread has a priority property that determines how big or small a slice of processor time . By default, the priority of thread is normal  , but you can customize priority by using any value in theThread Priorityenumeration i.e. define as below:

PriorityTest priority = new PriorityTest(); 
Thread thread1 = new Thread (priority.AboveNormal);


1. AboveNormal: For setting the highest priority.
 2. BelowNormal: you can be scheduled after threads with Normal priority and
before those with Lowest priority.
 3. Highest: you can be scheduled before threads with any other priority.
 4. Lowest: you can be scheduled after threads with any other priority.
 5. Normal: by default.

Thread Properties:
Threads also contain several useful properties, as shown in the follows:
1.     isAlive:If any thread are active it will returns true.

2.  isBackground :Gets or sets a Boolean that indicates if a thread is or should be a

background thread. Background threads are like foreground threads, but a

background thread does not prevent a process from stopping. Once all foreground

threads that belong to a process have stopped, the common language runtime

ends the process by calling the Abort method on background threads that are still

alive.


3.     Name : It returns the name of thread


4.  Priority :Gets or sets a value that is used by the operating system to prioritize

thread scheduling.


5.  ApartmentState :Gets or sets the threading model used for a particular thread.

Threading models are important when a thread calls unmanaged code.


6.   ThreadState:hold a value of thread state or state. 

For example, we are declaring one thread t using ThreadStart delegate . After that we start the thread t  and check t is alive or not .For the main thread to put sleep 2 millisecond until wait t finishes, Join also has overloads that take a millisecond interval or a TimeSpan object. And lastly call abort method to stopping thread of t. After stopping thread we want to restart the thread again but it will throw an exception.

 

using System;
using System.Threading;
namespace MultithreadingEx
{
    classProgram
    {
        staticvoid Main(string[] args)
        {
            Console.WriteLine(@"\n## Let us try to  use Thread Start/Stop/Join ");
            Console.WriteLine();
            Demo demo = newDemo();
            // Create the thread object via a ThreadStart delegate. This does not start the thread
            Thread t = newThread(newThreadStart(demo.CheckingThread));
            //start the thread
                  t.Start();
            //  while waiting for the started thread to become alive:
                  while (!t.IsAlive) ;
            // Put the Main thread to sleep for 2 millisecond to allow t to do some work:
                  Thread.Sleep(2);
            // Request that t be stopped
                      t.Abort();
            // Wait until t finishes. Join also has overloads that take a millisecond interval or a TimeSpan object.
                      t.Join();
            try
            {
                Console.WriteLine("\n ## Try to restart the Demo.CheckinThread thread again! ");
                     t.Start();
            }
            catch (ThreadStateException)
            {
                Console.Write("\n ThreadStateException trying to restart Demo.CheckinThread. ");
                Console.WriteLine("\n Expected since aborted so can’t restarted thread again.");
            }
            Console.ReadKey();
        }
    }
}

 Output:

Multi-threading in C#

 

 


Updated 07-Sep-2019

Leave Comment

Comments

Liked By