Multithreaded Programming

A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus multithreading is a specialized form of multitasking.

Process: A process is, in essence, a program that is executing.

Thread: A thread is a dispatchable unit of executable code.

Types of Multitasking: There are two distinct types of multitasking: Process-Based Multitasking and Thread Based Multitasking. C# and .NET Framework supports both the types.

Process-Based Multitasking: Process-Based Multitasking handles the concurrent execution of programs.

Thread Based Multitasking: Thread Based Multitasking deals with concurrent execution of pieces of the same program.

States of a Thread: There are various states of a thread as mentioned below:

1)       Running
2)       Ready to run – as soon as it gets CPU time.
3)       Suspended – a running thread can be suspended (temporary halt to its execution).
4)       Resume – a suspended thread can later be resumed.
5)       Blocked – a thread can be blocked when waiting for a response.
6)       Terminated – a thread can be terminated, in which case its execution ends and cannot be resumed.

Threads in .NET Framework: The .Net Framework defines two types of threads: foreground and background. By default, when we create a thread, it is a foreground thread, but it can be changed to a background thread.
A background thread is automatically terminated when all foreground threads in its process have stopped.

The classes that support multithreaded programming are defined in the System.Threading namespace.

The Thread Class: C# multithreading system is built upon the Thread class, which encapsulates a thread of execution. The Thread class is sealed. It defines several methods and properties that help manage threads.

Creating and Starting a Thread: To create a thread, we instantiate an object of type Thread. The simplest Thread constructor is shown below:

public Thread (ThreadStart entryPoint)

Here, entryPoint is the name of the method that will be called to begin execution of the thread.

ThreadStart is a delegate defined by the .NET Framework as shown below:

public delegate void ThreadStart ()

The entryPoint method must have a void return type and take no arguments.

The newly created thread starts running after we call its Start() method. Start() is defined by Thread and calls the method specified by entryPoint. Form of Start() is shown below:

public void Start()

Note: If we try to call Start() on a thread that has already been started, a ThreadStateException will be thrown.

No comments:

Post a Comment