Join, Sleep and Abort methods in C# Threading
There are lots of methods in Thread class. Here I am discussing about three main
methods which is widely used in multithreading. Join method are used to calling
threads and execute it until thread
not terminate, i.e Join method waits for finishing other threads by calling its
join method.
Sleep methods are generally used for suspends thread for specified time and
after that time it will notify automatically in process. Abort method are used
to terminate the threads.
Example:
To use these method use System.Threading namespace and writes the following
code.
using
System.Threading;
namespace
ThreadTest
{
class
Program
{
static
void Main(string[] args)
{
// Creating thread object to strat it
Thread
threadB =
new Thread(ThreadB);
Thread
threadC =
new Thread(ThreadC);
Console.WriteLine("Threads
started :");
// Assign thread name
threadB.Name =
"Child thread";
// Start thread B
threadB.Start();
threadC.Start();
// join the Second thread after finishing the
first thread
threadB.Join();
//Assign main thread name
Thread.CurrentThread.Name =
"Main Thread";
//Thread A executes 10 times
for (int i = 0; i < 10; i++)
{
if (i == 4)
// Join thread c
threadC.Join();
if (i == 5)
{
// Terminate
thread C
threadC.Abort();
}
Console.WriteLine(Thread.CurrentThread.Name);
Thread.Sleep(100);
}
Console.WriteLine("Threads
completed");
Console.ReadKey();
}
public
static void
ThreadB()
{
// Executes thread B 10 times
for(int i=0;i<10;i++)
{
// Suspends
thread for 2 seconds
Thread.Sleep(200);
Console.WriteLine("Thread B");
}
}
public
static void
ThreadC()
{
// Executes thread B 10 times
for (int i = 0; i < 20; i++)
{
// Suspends
thread for 2 seconds
Thread.Sleep(200);
Console.WriteLine("Thread C");
}
}
}
}
Output:
|