Multithreading in C#
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
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
Starting and Stopping
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 = new Thread(new ThreadStart());
// For starting the thread
stop the execution of a thread, using the Abort method,
as shown as follows.
following are most common methods are using to control individual thread:
Sleep() : Pauses a thread for a specified time(In milliseconds).
Suspend():Pauses a thread
when it reaches a safe point.
Resume(): Restarts a suspended thread.
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.
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 the Thread Priority
enumeration 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.
Threads also contain
several useful properties, as shown in the follows:
isAlive: If any thread are active it will returns true.
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.
Name : It returns
the name of thread
Priority : Gets or sets a value that is used by the operating system to
prioritize thread scheduling.
ApartmentState : Gets or sets the threading model used for a particular thread.
Threading models are important when a thread calls unmanaged code.
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.
static void Main(string args)
Console.WriteLine(@"\n## Let us try to use Thread Start/Stop/Join ");
Demo demo = new Demo();
// Create the thread object via a ThreadStart delegate. This does not start the thread
Thread t = new Thread(new ThreadStart(demo.CheckingThread));
//start the thread
// 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:
// Request that t be stopped
// Wait until t finishes. Join also has overloads that take a millisecond interval or a TimeSpan object.
Console.WriteLine("\n ## Try to restart the Demo.CheckinThread thread again! ");
Console.Write("\n ThreadStateException trying to restart Demo.CheckinThread. ");
Console.WriteLine("\n Expected since aborted so can’t restarted thread again.");