Threading:
• A thread is the basic unit to which the OS allocates processor time
• Namespace: System.Threading
• A .net program has minimum of two threads, main and garbage collector
Code Listing: Threading
using System;
using System.Threading;
public class Worker
{
public void DoWork()
{
while(! _shouldStop) { Console.WriteLine(“Worker thread working...”); }
Console.WriteLine(“Worker thread terminating...”);
}
public void RequestStop()
{
_shouldStop = true;
}
private volatile bool _shouldStop;
}
public class WorkerThreadExample
{
static void Main()
{
Worker workerobject = new Worker();
Thread workerThread = new Thread(workerObject.DoWork);
workerThread.Start();
Console.WriteLine(“Main thread:starting worker thread...”);
while(workerThread.IsAlive);
Thread.Sleep(1);
workerObject.RequestStop();
workerThread.Join();
Console.WriteLine(“Main Thread: Worker thread terminated...”);
}
}
No comments:
Post a Comment