Home >Backend Development >C#.Net Tutorial >C# Thread
The following article provides an outline for C# Thread. The execution path of the program is defined as thread and an unique flow of control is defined by each thread. Different paths of execution or threads must be set where each thread is responsible for a particular job when the application comprises of operations that are complicated and time consuming. These threads processes which are light weighted and the modern operating systems implementing the concurrent programming is one of the examples of using threads and by using threads, the central Processing Unit’s cycle wastages are saved and the efficiency of the application is increased.
Syntax:
public sealed class Thread: System.Runtime.ConstrainedExecution.CriticalFinalizerObject
The time an object of System.Threading.Thread class is created when the life cycle of the thread starts. When there is termination of thread or completion of execution of thread, the thread is created and ends.
There are several states in the life cycle of a thread.
1. The unstarted state: This state is a situation whenever the start method is not called but an instance of the thread is created.
2. The Ready state: This state is a situation when the thread is all set to run and is waiting for the cycle of Central Processing Unit.
3. The Not Runnable State: This state is a situation when the thread cannot be executed when:
4. The dead State: This state is a situation when the execution of the thread is complete, or the execution of the thread is aborted.
Below program demonstrates the execution of main thread:
Code:
using System; using System.Threading; //a namespace called multithreading is created namespace Multithreading { //a class called mainthread is created under multithreading namespace class MainThread { //main method is called static void Main(string[] args) { //an instance of the thread class is created Thread thr = Thread.CurrentThread; //Name method of thread class is accessed using the instance of the thread class thr.Name = "Thread Class"; //the content is displayed as the output Console.WriteLine("Welcome to {0}", thr.Name); Console.ReadKey(); } } }
Output:
In the above program, a namespace called multithreading is created. Then a class called mainthread is created under multithreading namespace. Then a main method is called. Then an instance of the thread class is created. Then Name method of thread class is accessed using the instance of the thread class. Finally the output is displayed on the screen.
Given below are the several methods of thread class:
Whenever Abort() method is invoked on a thread, ThreadAbortException is raised and the process of termination of thread begins. The termination of thread is caused by calling this method.
Example:
Code:
using System; using System.Threading; class ExThread { public void thr() { for (int y = 0; y < 3; y++) { Console.WriteLine(y); } } } class Example { public static void Main() { ExThread ob = new ExThread(); Thread th = new Thread(new ThreadStart(ob.thr)); th.Start(); Console.WriteLine("Aborting the thread"); th.Abort(); } }
Output:
Whenever Interrupt() method is called, a thread which is in the thread state of WaitSleepJoin is interrupted.
Whenever Join() method is called, a calling thread is blocked until the termination of a thread and the standard COM and SendMessage pumping are continued to be performed along with blocking of the thread.
Example to implement Interrupt() and Join():
Code:
using System; using System.Threading; class Thr { Thread th; public Thr(String name1) { th = new Thread(this.Runaway); th.Name = name1; th.Start(); } public void Runaway() { Thread th1 = Thread.CurrentThread; try { Console.WriteLine(" Execution of " + th1.Name + " has begun"); for(int y=0; y<3; y++) { Console.WriteLine(" Printing of " + th1.Name + " has begun" + y); Thread.Sleep(200); } Console.WriteLine(" Execution of " + th1.Name + " is finished"); } catch(ThreadInterruptedException e) { Console.WriteLine("Thread Interruption" + e); } } public static void Main(String[] ar) { Thr ob = new Thr("Thread demo"); ob.th.Interrupt(); ob.th.Join(); } }
Output:
Whenever ResetAbort() method is called, the termination request for the current thread is cancelled.
Example:
Code:
using System; using System.Threading; using System.Security.Permissions; class Thread1 { public void Jobthread() { try { for (int r = 0; r < 3; r++) { Console.WriteLine(" Working of thread has begun "); Thread.Sleep(10); } } catch (ThreadAbortException e) { Console.WriteLine("ThreadAbortException is caught and must be reset"); Console.WriteLine("The message looks like this: {0}", e.Message); Thread.ResetAbort(); } Console.WriteLine("Thread is working fine"); Thread.Sleep(200); Console.WriteLine("Thread is done"); } } class Driver { public static void Main() { Thread1 obj = new Thread1(); Thread Th = new Thread(obj.Jobthread); Th.Start(); Thread.Sleep(100); Console.WriteLine("thread abort"); Th.Abort(); Th.Join(); Console.WriteLine("end of main thread"); } }
Output:
Whenever Start() method is called, a thread is started.
Example:
Code:
using System; using System.Threading; class Test { static void Main() { Thread td = new Thread (new ThreadStart (Got)); td.Start(); } static void Got() { Console.WriteLine ("this is thread Start() method"); } }
Output:
Whenever Sleep(int millisecondsTimeout) method is called, the thread is paused for the specified time period.
Example:
Code:
using System; using System.Threading; namespace Examplethr { class MyThread { static void Main(string[] args) { Thread th = Thread.CurrentThread; th.Name = "This is the First Thread"; Console.WriteLine("The Name of the thread is : {0}", th.Name); Console.WriteLine("The priority of the thread is : {0}", th.Priority); Console.WriteLine("Pausing the child thread"); // using Sleep() method Thread.Sleep(100); Console.WriteLine("Resuming the child thread"); Console.ReadKey(); } } }
Output:
Whenever Suspend() method is called, the current thread is suspended if it is not suspended.
Whenever Resume() method is called, the suspended thread is resumed.
Whenever Yield() method is called, the calling thread must result in execution to the other thread which is ready to start running on the current processor. The thread to yield to is selected by the operating system.
Example to implement Suspend() Resume() and Yield()
Code:
using System; using System.Runtime.CompilerServices; using System.Threading; class Program { public static void Main () { bool finish = false; Thread th = new Thread (() => { while (!finish) {} }); Thread th1 = new Thread (() => { while (!finish) { GC.Collect (); Thread.Yield (); } }); th.Start (); th1.Start (); Thread.Sleep (10); for (int j = 0; j < 5 * 4 * 2; ++j) { th.Suspend (); Thread.Yield (); th.Resume (); if ((j + 1) % (5) == 0) Console.Write ("Hello "); if ((j + 1) % (5 * 4) == 0) Console.WriteLine (); } finish = true; th.Join (); th1.Join (); } }
Output:
The above is the detailed content of C# Thread. For more information, please follow other related articles on the PHP Chinese website!