Threading – running different parts of the program at “once”

A thread is when you “spawn” off another process (a process is like another program running within itself).

The operating system gives the impression that it is running allot of programs at the same time, but what is happening that allot of processes (programs) have access to the CPU for a limited amount of time, e.g. 10 milliseconds, and then leave the CPU execution stage whilst another process will enter there CPU execution stage (this is the part where the program is actually doing something).

To start with lets first create a method that is run within new thread, here we are just going to output a message and sleep for a bit, loop this over for 10 times.

// the method to create as a threadable method
public static void RunThisMethod()
{
	for (int i =0; i < 10; i++)
	{
		Console.WriteLine("RunThisMethod number : "+i.ToString() + " Sleep for 45");
		Thread.Sleep(45);
	}
}

Now lets create a thread, since a Thread has to be a delegated method but with .net 2 and above the .net environment will pick the correct delegate for you, so this means that you can just pass in the method name to the Thread class and that is it

	Thread theThread = new Thread(RunThisMethod);

To start the new Thread, it is as easy as start

	theThread.Start();

Here is the full source code, for demoing how the main and the runMyMethod flip between each other (e.g. each process has time in the processor(s) to run)

using System;
using System.Threading;
 
namespace myThread
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			// initialize the RunThisMethod as a thread
			Thread theThread = new Thread(RunThisMethod);
			theThread.Start();
 
			for (int j = 0; j < 5; j++)
			{
				Console.WriteLine("Main method number : "+j.ToString()+" Sleep for 100");
				Thread.Sleep(100);
			}
		}
 
		// the method to create as a threadable method
		public static void RunThisMethod()
		{
			for (int i =0; i < 10; i++)
			{
				Console.WriteLine("RunThisMethod number : "+i.ToString() + " Sleep for 45");
				Thread.Sleep(45);
			}
		}
	}
}

and here would be the output

Main method number : 0 Sleep for 100
RunThisMethod number : 0 Sleep for 45
RunThisMethod number : 1 Sleep for 45
RunThisMethod number : 2 Sleep for 45
Main method number : 1 Sleep for 100
RunThisMethod number : 3 Sleep for 45
RunThisMethod number : 4 Sleep for 45
Main method number : 2 Sleep for 100
RunThisMethod number : 5 Sleep for 45
RunThisMethod number : 6 Sleep for 45
Main method number : 3 Sleep for 100
RunThisMethod number : 7 Sleep for 45
RunThisMethod number : 8 Sleep for 45
Main method number : 4 Sleep for 100
RunThisMethod number : 9 Sleep for 45

Leave a Reply

Your email address will not be published.