Managing threads

Threads can be created by creating a new instance of the System.Threading thread class and providing the name of the method that you want to execute on a new thread to the constructor. Using this class gives us more control and configuration of the program; for example, you can set the priority of the thread and whether it is a long-running thread, abort it, put it to sleep, and implement advanced configuration options. The Thread.Start method is used to create a thread call, while the Thread.Abort method is used to terminate the execution of a thread. The abort method raises ThreadAbortException when invoked. Thread.Sleep can be used to pause the execution of the thread for a certain amount of time. Finally, the Thread.Interrupt method is used to interrupt a blocked thread.

Let's understand these concepts by looking at a few examples.

In the following code, ThreadSample is the primary thread, which starts the worker thread. The worker thread loops 10 times and writes to the console, letting the process know it has completed. After starting the worker thread, the primary thread loops four times. Note that the output depends on the environment you are running this program on. Try to change the seconds in the thread.sleep statement and observe the output:

internal class ThreadingSamples
{
public static void ThreadSample()
{
Console.WriteLine("Primary thread: Starting a new worker thread.");
Thread t = new Thread(new ThreadStart(ThreadOne));
t.Start();
//Thread.Sleep(1);
for (int i = 0; i < 4; i++)
{
Console.WriteLine("Primary thread: Do something().");
Thread.Sleep(1);

}
Console.WriteLine("Primary thread: Call Join(), to wait until ThreadOne ends.");
t.Join();
Console.WriteLine("Primary thread: ThreadOne.Join has returned.");
}

public static void ThreadOne()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("ThreadOne running: {0}", i);
Thread.Sleep(0);
}
}
}

Let's check the output of our program. ThreadOne starts its execution first and initiates 10 different worker threads and then the primary thread is executed. If you delay the execution of ThreadOne by using sleep, you will see the primary thread wait until ThreadOne returns:

When the program is executed, a foreground thread is created automatically to execute the code. This primary thread then creates worker threads as required to execute the sections of the code from the same process. As you can see, the thread takes a delegate in its constructor. 

In the preceding program, we used thread.join, which lets the primary thread wait until all the worker threads have completed their execution. Also, Thread.Sleep(0) tells Windows that the current thread has finished its execution so that a context switch can happen instead of Windows having to wait for the allocated time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.19.75