Multi-threading
Is a concept to execute multiple tasks or process simultaneously. Basically multi-threading enables paths to your application to execute multiple processes. Multi-threading can be achieved in C# using System.Threading name space which provides complete control over threading.
Let’s write example code where we will execute two different methods to print numbers using loop and identify the result:
using System; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //Create thread 1 Thread threadOne= new Thread(new ThreadStart(OutputOne)); Thread threadTwo = new Thread(new ThreadStart(OutputTwo)); threadOne.Start(); threadTwo.Start(); Console.ReadKey(); } public static void OutputOne() { for (int i = 1; i <= 10; i++) { Console.WriteLine("OutputOne is writing : " + i); } } public static void OutputTwo() { for (int i = 1; i <= 10; i++) { Console.WriteLine("OutputTwo is writing : " + i); } } } }
Methods
- Sleep: method pauses the execution for specific time interval
- CurrentThread: provides object of current thread
- Start: starts a thread execution
- Abort: aborts a thread execution
- Suspend: suspends or pauses a thread for given time
- Resume: resumes a suspended thread immediately
- Join: makes current thread wait for other thread to finish
Properties
- Name: get or sets name of a thread
- Priority: a property of type System.Threading.ThreadPriority to explicitly set the priority of a thread
- IsAlive: returns state of a thread (alive or terminated), its a boolean property
- ThreadState: a property of type System.Threading.ThreadState helps retrieving thread state.