Monday, August 17, 2009

Making Threads in C#

Threads are means of splitting your program into two or more programs that execute parallel to each other. A simple code for making threads in C# (.NET) is written below. When we write this code, our main program will continue its execution from the end of this code, but before that it will create another process/program that will execute a function whose name will be written as explained below.

On top of the page write down the following:

using System.Threading;

// This will act like including a header file which deals with threads

Now to make a thread, write down the following:

Thread T = new Thread(new ThreadStart( /* Name Of Function */ ));

// Replace the text /* Name Of Function */ by the name of function that you want your newly made thread to execute

// Now your thread has been created but has not started its execution yet

T.Start();

// Write this command and the thread will start its execution

// Another command that is used with threads is:

T.Join();

// With this command the thread T will wait till all the previously created threads to finish their execution, before T will start its own execution

The same code can be written inside a for loop and any number of threads can be created.

2 comments:

  1. Very informative blog Haroon. I was kind of random searching about your name on google when i came to know about your blog... I was also thinking of making my own blog and your blog kind of helped me a lot.

    ReplyDelete