Thread
Thread is the smallest piece of program that can be managed by operating system. A process may consist of many threads. Threads run concurrently. Basically they work in queue which is scheduled by operating system. For a small amount of time processor’s resources are given to one thread then to another. While one thread is being executed others wait in a queue and when any other thread is to get executed the data and content associated with current thread is stored in a memory stack which is replaced in processor’s register when that thread is called to be executed.
Threads in C#:
Thread Declaration
Threads are declared in C# using System.threading() and then using following command
Thread A=new Thread(callBackFunction());
where callBackFunction is the function that will be called when this thread starts executing.
Thread Initialization
A thread can be started once declared using thread.start() function
A.start();
Thread Abortion
A thread is aborted using thread.abort() funciton
A.abort();
Thread Suspension & restoration
To suspend a thread for a while for like calling another one we use thread.suspend()
A.suspend();
To resume this thread we use
A.resume();
C# Code for threads:
Following is a code for multiple thread execution its very simple and self explaining for any query comment below it will be appreciated. Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace threads
{
class Program
{
public static void func1(){
while(true)
Console.WriteLine(“Thread A running”);
}
public static void func2()
{
while (true)
Console.WriteLine(“Thread B running”);
}
static void Main(string[] args)
{
//declaring two threads A & B
Thread A = new Thread(func1);
Thread B = new Thread(func2);
//starting thread A
A.Start();
for (int i = 0; i < 500000000; i++) {
;
}
//aborting thread A
A.Abort();
//starting thread B
B.Start();
for (int i = 0; i < 500000000; i++)
{
;
}
//aborting B
B.Abort();
//for pausing output
Console.ReadLine();
}
}
}