Thursday, 26 June 2014

MultiThreading Concept and Thread State in C# .Net


Thread in C# .Net………………………….

Before we start this topic we have to know about differences b/w Multitasking Multiprocessing and Multi-Threading

Multitasking:  Multitasking, in an operating system, is allowing a user to perform more than one computer task (such as the operation of an application program) at a time. For example Microsoft Windows 2000, IBM's OS/390, and Linux etc.
Those operating system which allow to perform single task at the same time is called Single tasking operating system For example DOS (Disk Operating System)

These are two types concept in Multitasking
1.    Multi-Processing
2.    Multi-Threading

Multiprocessing:  computer system's ability to support more than one process or program at the same time. Multiprocessing operating systems enable several programs to run concurrently. UNIX is one of the most widely used multiprocessing systems, but there are many others, including Windows-Xp etc. Multiprocessing systems are much more complicated than single-process systems because the operating system must allocate resources to competing processes in a reasonable manner.
It refers to the utilization of multiple CPUs in a single computer system. This is also called parallel processing
 
Multithreading: A thread is defined as the execution path of a program. You can define a unique flow of control in a program using thread .Thread are used to run application that perform large and complex computations. Other ways you can say Thread is smallest unit of code that dispatched to C.P.U. for execution. If dispatched multiple threads to C P U to run all thread parallel is call multithreading programming
For  Example:  CPU (Central  Processing  Unit) performs various complex tasks simultaneously .The  process include three different  tasks such as listening  songs with media player,inslalling software and  writing with ms office .All the process are handled  by separate threads..
Single-Threaded Application: A process that is executed using one thread is known as a single-thread-process. A single-threaded application can perform only one task at a time. Means you have wait for one task to complete before another task can start.
Multi-Threaded Application: A process that create two or more threads is called multi-threaded-process


Threads vs. Processes: A thread is analogous to the operating system process in which your application runs. Just as processes run in parallel on a computer, threads run in parallel within a single process. Processes are fully isolated from each other; threads have just a limited degree of isolation. In particular, threads share (heap) memory with other threads running in the same application. This, in part, is why threading is useful: one thread can fetch data in the background, for instance, while another thread can display the data as it arrives.

Thread States: Life Cycle of a Thread

Thread has one of several thread states this section discusses these states and the transitions between states. Two classes critical for multithreaded applications are Thread and Monitor (System. Threading namespace). This section also discusses several methods of classes Thread and Monitor that cause state transitions.
A new thread begins its lifecycle in the Un-started state. The thread remains in the Un-started state until the program calls Thread method Start, which places the thread in the Started state (sometimes called the Ready or Run able state) and immediately returns control to the calling thread. Then the thread that invoked Start, the newly Started thread and any other threads in the program execute concurrently. 

 Type of Several Thread State in C# .Net

·         UnStarted: Thread is created within the common language run time but not started still.

·         Running: After a Thread calls Start method

·         Wait/Sleep/Join: After a Thread calls its wait or Sleep or Join method.

·         Resume: causes the suspended Thread to resume its execution.

·         Suspended: Thread responds to a Suspend method call.

·         Stopped: The Thread is Stopped, either normally or Aborted.

Pictorial Representation Thread states in c# .Net



For Example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
// using this name space for Threading
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ThreadConcept
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

Thread th;

private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
th = new Thread(fun1);

}
// Thread  function
public void fun1()
{
for (int i = 0; i < 30000; i++)
{
try
{
txtno.Text = i.ToString();
}
catch (ThreadAbortException ex)
{
if (MessageBox.Show("Do you want to abort the thread", "Thread Abort Request", MessageBoxButtons.YesNo) == DialogResult.No)
{
Thread.ResetAbort();
}
}
}

}
// Thread Start
private void btnStart_Click(object sender, EventArgs e)
{
if(th.ThreadState.ToString() != "Aborted")
th.Start();

}

// code for find current state of thread
private void btnthreadstate_Click(object sender, EventArgs e)
{
MessageBox.Show("Thread State is =>   "+th.ThreadState);
}

// code for how to abort  thread
private void btnThreadAbort_Click(object sender, EventArgs e)
{
th.Abort();
}

// code for suspend thread
private void btnSuspend_Click(object sender, EventArgs e)
{
if (th.ThreadState.ToString() == "Aborted")
{
MessageBox.Show("You can not Suspend this Thread  because Thread state is Aborted");
}
if (th.ThreadState.ToString() == "Running")
{
th.Suspend();
MessageBox.Show(th.ThreadState.ToString());
}
}

// code for Resume thread
private void btnResume_Click(object sender, EventArgs e)
{

if (th.ThreadState.ToString() == "Aborted")
{
MessageBox.Show("You can not Resume this Thread  because Thread state is Aborted");
}
if (th.ThreadState.ToString() == "Suspended")
{
th.Resume();
MessageBox.Show(th.ThreadState.ToString());
}

}
// code for check thread is live or dead state
private void btnIsAlive_Click(object sender, EventArgs e)
{
if (th.IsAlive == true)
{
MessageBox.Show("Thread is live");
}
else
{
MessageBox.Show("Thread dead");
}
}
}
}

Result



1 comments: