Multithreaded Programming Using C#

Introduction

Threading is a lightweight process. With the help of threads we can increase the response time of the application. To use multithreading we have to use the Threading namespace which is included in System. The System.Threading namespace includes everything we need for multi threading. Now lets see the first program.

This program has a class MyThread which has two static functions Thread1 and Thread2. To make a thread you have to make an object of class Thread. The constructor of this class takes a reference of a ThreadStart class. This constructor can send two types of exceptions; ArgumentNullException when the parameter is a null reference or a Security Exception when program does not have permission to create thread.

The parameter of the Thread class is reference to a ThreadStart class. ThreadStart class points to the method that should be executed first when a thread is started. The parameter is the name of the function, which is considered as a thread function. Thread1 is a static function so we give it with the name of class name without making an object of the class. The thread starts execution with Start() method of the Thread class. The output of this program is

It is also not necessary to create the object of ThreadStart at the time of passing paramaters in the constructor. You can create the object of ThreadStart and pass it as a parameter of Thread. Let's see this program.

The Sleep method suspends the execution of the thread for a specified time. Sleep is a static method so it can be used without making an object of Thread. There are two overloaded versions of Sleep(), one function takes time in milliseconds and second method take a reference of an instance of the TimeSpan structure.

Now the thread sleeps for one millisecond and gives the second thread an opportunity to execute. The output of this program is

Before start thread
Hello world 0
Hello world 0
Hello world 1
Hello world 1
Hello world 2
Hello world 2
Hello world 3
Hello world 3
Hello world 4
Hello world 4
Hello world 5
Hello world 5
Hello world 6
Hello world 6
Hello world 7
Hello world 7
Hello world 8
Hello world 8
Hello world 9
Hello world 9

Now both threads seem to execute in parallel. Here is a program which shows the usage of the other overloaded method of sleep.

The TimeSpan structure has four oveloaded constructors. The first take only one long paramater to a specified number of ticks, the second takes three int paramters for hours, mins and seconds respectively, the third take three int parameters for days, hours, mins and seconds and fourth overloaded constructor takes five parameter for days, hours, mins, seconds and milliseconds. The output of this program is the same except this program prints a new value after one second.

The Sleep method throws three type of exceptions; ArgumentException, when the time-out value is less than zero, ThreadInterruptedException when the thread is interrupted while sleeping and SecurityException when caller don’t have the appropriate permissions.

Let's see the program showing to handle the situation when the argument of Sleep() is negative.

This program handles all the three exceptions. Take a look at the first line of the code. Here I use one more namespace: System.Security. The exception class SecurityException is defined in this namespace.

We have to get the reference of the thread in our thread function to get the name of the thread. We can get the current thread name by using CurrentThread. CurrentThread is a static property of the Thread class. This property throws only one exception: SecurityException when the caller doesn’t have appropriate Security Permissions.

There are two methods to terminate thread. The first one is Stop() and second is Abort(). Don’t use Stop(), this function will not be in future releases of .NET; it will give you a warning. There are two overloaded methods of Abort. The first one executed without parameter and the second takes reference of Object as a parameter. This method throws ThreadAbortException that is not caught. Let’s see this program

Here we catch ThreadStatException and we use the ToString method of this class. ToString method returns the fully qualified name of this exception, and possibly error message, name of the inner exception and stack trace.

We can also wait for terminating the thread by using the Join method. This method has three overloaded methods. First without parameter waits till the thread dies, second takes one int parameter and waits for the thread to die or for specified time to expire and third take a reference of an instance of the TimeSpan structure. See the following program.

Now the program waits for the first thread until it finishes and second thread for one second.

Threads can be executed in two ways: either in background or in foreground. A background thread is finished when the application is terminated, on the other hand foreground thread is not waiting for the termination of the application. We can set the execution of thread is by using IsBackground property. This program show the usage of this.

This output shows when your application terminates that both background threads are also terminated.

We can also assign the priority of our thread. We can assign the priority of a thread by using ThreadPriority priority of the Thread class. This program shows the usage of the priority property of the thread.

Two points I want to make on the multiple threading on real world programming.
<1>Two threads accessing two different memory location that will be OK because they are doing separate things. In that case, concurrency issue unlikely occurrs. so as to 'n' threading.
<2>Two threads accessing one block of memory location then one has to wait for the another. In that case creating more threads is just useless. eg. If you have n threads accessing one row on a table on SQL DB, then it will be case 2. All other threads have to wait until current job got done by previous one. That is the limitation of the concurrency programming.
Some people misunderstood the idea. They may think more threads means more quicker to get job done. That is totally wrong. It will be more slower oppositely if all threads are doing same job.
To be frankly, I really hate multiple threads. It is always messed up. LOL.....
Stefan Sze

I thank that threading very hard to programming it, but now it became easy to use and to understand it by this articles.
congratulation to programmers who don't know how to use threading, now you can understand it by this article.

I hear .Start() is no longer support for future .NET library and is being phase out.
Can someone offer alternative tutorial covering mutex, I think this is a missing link.
Thanks

>It's not so much what you have to learn if you accept weird theories, it's what you have to unlearn. (Isaac Asimov)
>Life's journey is not to arrive at the grave safely in a well preserved body,but rather to skid in sideways, totally worn out, shouting "...holy sh*t...what a ride! [Riscy]

1. I have save detail method on server which take long time to dave data in database because it is inserting 10000+ records each time and my frond end application hangs for 2-3 minutes.

Through safe threading i want to achvive this task and I also want to know how many threads are running on server because this methods might be call from other user.
Can i also get % of complition of task by each thread?

I wish to know how compiler will interpet following situation.
Instead of creating two object MyThread, I create only one.
// part of program3
...
public static void Main() {
Console.WriteLine("Before start thread");