this blog contains information for .net and sql stuffs. You can find various tips and tricks to overcome problem you may be facing in ...

Friday, May 7, 2010

Threading in .net (Part -2)

In previous post, we have got idea of what is threading and how it can be done easily by calling ThreadPool.QueueUserWorkItem. But threading is not that mean only we need more control on our threading activity.

Like we need to ensure that all thread must work, give priority to my thread than other once, weather my thread has been completed or not, what is status of my thread etc.. all thing can be done by various type of mechanism provided by .net. Yes it’s surely a tedious and complex task to implement but if we do it carefully it not only reduces response time but application behaves very nicely and manages resources.

ThreadPool.QueueUserWorkItem provides a way to run thread in back ground and let it run until it finish. For more control on thread we can create instance of thread, we can even control start, pause, abort, priority. We can handle ThreadAbortException when thread has been aborted.

àCreate thread instance

Thread myThread = new Thread(new ThreadStart(myWork));

àStart thread


àWait for some time to run myThread


àAbort myThread


myWork method has following implementation

public static void myWork()


Console.WriteLine("myWork is running on another thread.");





catch (ThreadAbortException ex)


Console.WriteLine("myWork was aborted.");




Console.WriteLine("Use finally to close all open resources.");


Console.WriteLine("myWork has ended.");


In above code “myWork has ended” will never display as I have aborted thread. If I comment that line that it will be displayed.

We can call Thread.Suspend and Thread.Resume to stop and resume thread execution but sometime they can create problem. Say for example I am stopping a thread which has acquired my printer, so it will create deadlock condition as my other thread may need printer.

We can set thread priority before starting thread by ThreadPriority enumeration. Enumeration has following values.






By default foreground and background run on normal priority.

Thread’s state can be checked with Thread.ThreadState property. There are various types of it like Unstarted, Running, Stopped, Suspended, Aborted etc. At a time a thread may have one or more thread state.

Sometime there is requirement to know status of thread which is running in background we want to pass some data to thread and let us know what is the output of that data after certain time elapsed. We can achieve this task by creating delegate and callback. For that we need to create a delegate at class level and a method to handle that delegate. Create a class for which you want to run in background, add delegate to class. Create an instance of class and in constructor pass delegate with appropriate method.

When there are more than one thread runs simultaneously, situation may happen it acquires resource and in turn deadlock. So it means instead of improvement in performance our application become slow and unresponsive. At that time we need to manage resource by synchronizing thread resource.

Use lock keyword in C# and SynLock keyword in It does not allow using resource of any other thread till it completes it work. One thing should be kept in mind that these keywords work only with reference type not on value type.

When there is requirement of separate read and write lock on resource we can use ReaderWriterLock class. Create instance of this class and use separate read and write lock.

ReaderWriterLock rwl = new ReaderWriterLock()

To acquire read lock


Release reader lock


Acquire writer lock and release it.



Another method to synchronize thread is to use object of Interlocked class. It will add numeric value to thread. It also provides various numeric methods.

There are also so many things to wait for thread to complete and start another thread once complete previous one.

NOTE: In visual basic we need to add attribute to main method to run main thread as multithread. MTA (Multithread Apartment) is by default provided in C#, so there is no need to add it. MTA supports calling WaitHandle.WaitAll.

No comments: