C# Multithreading


Introduction:

In this article let us see aboutmultithreading. Multithreaded applications provide the illusion thatnumerous activities are happening at more or less the same time. In C#the System.Threading namespace provides a number of types that enablemultithreaded programming.

Threading in C#

System.Threading Namespace

The System.Threading Namespace provides anumber of types that enable multi-threading programming. In addition toproviding types that represent a particular thread, this namespace alsodescribe types that can handle a collection of threads (Thread Pool), asimple (Non -GUI based) Timer class and several types to providesynchronized access to shared data.

The most primitive of all types in the System.Threading namespace is Thread.Thread:

Represents a thread that executes with in theCLR. Using this type, one can able to spawn additional threads in theowning AppDomain.This type defines a number of methods (both static andshared) that allow us to create new threads from a current thread, aswell as suspend, stop, and destroy a given thread.

The following example will demonstrate Spawning of Secondary threads using C#.

internal class EmployeeClass
{
public void Performjob()
{

// Get some information about the thread.

Console.Writeline("ID of Employee thread is {0}",
Thread.CurrentThread.GetHashCode() );

//Do the job.
Console.write("Employee says:");
for (int i=0;i<10;i++)
{
Console.write(i +",");
}
console.writeline();
}
}

The above code simply prints out a series of numbers by way of the performjob() member function.

Now assume that a class (Main class) creates anew instance of EmployeeClass. In order for the Main class to continueprocessing its workflow, it creates and starts a new thread that isused by the job.In the code below, notice that Thread type requests a new Threadstartdelegate type:

Public class Mainclass
{
public static int Main (string[] args)
{
Console.Writeline("ID of primary thread is {0}",
Thread.CurrentTHread.GetHashCode() );

// Make Employee class.

EmployeeClass j = new EmployeeClass();

// Now make and start the background thread.

Thread backgroundThread =
new Thread(new ThreadStart(j.Performjob));
backgroundThread.Start();
return 0;
}
}

If we run the application we would find the following result.

ID of primary thread is: 2
ID of Employee thread is: 11
Employee says: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
Press any key to continue

From the above example one can easily know how to spawning the secondary Threads.

Let us see another example regarding two active threads.

internal class EmployeeClass
{
public void Performjob()
{
// Get some information about the thread.

Console.Writeline("ID of Employee thread is {0}",
Thread.CurrentThread.GetHashCode() );

//Do the job.
Console.write("Employee says:");
for (int i = 0; i < 20000 ; i++)
{
Console.write(i +",");
}
console.writeline();
}
}

Public class Mainclass
{
public static int Main (string[] args)
{
// Make Employee class
…………
//Now make the thread.
…………
//Now while background thread is working
//do some additional work.
MessageBox.show("BUSY");
return(0);
}
}

If we run this application we would see thatthe message box is displayed and it can be moved around the desktop,while the background Employee thread is busy pumping numbers to theconsole.

Thread Synchronization:

A multithreaded application usually hasresources that can be accessed from multiple threads; for example, aglobal variable that is incremented or decremented by multiple threads.It is sometimes desirable to prevent multiple threads from concurrentlyaltering the state of a resource. The .NET Framework includes severalclasses and data types that we can use to synchronize actions performedby two threads.

The simplest case is if we have a sharedvariable that we need to update from different threads. To do this, wecan use the System.Threading.Interlocked class. For example, toincrement or decrement the shared variable called num, we'd writeInterlocked.Increment(num) or Interlocked.Decrement(num). we can alsouse Interlocked to set the variables to a specific value or to checkthe equality of two variables.

If there's a section of code in an object'smethod that should not be accessed concurrently by multiple threads, wecan use the Monitor class to acquire a lock on that object by callingMonitor.Enter(object). Any other thread wanting to execute the samecode would need to acquire the same lock and will be paused until thefirst thread releases the lock by calling Monitor. Exit(object).

For more control over thread synchronizationor for cross-process synchronization, use the Mutex class, which is anamed synchronization object that can be obtained from any thread inany process. Once we create or obtain the mutex, we use its GetHandlemethod to (as we'd expect) get a handle that we can use with theWaitHandle.WaitAny or WaitHandle.WaitAll methods. These two methods areblocking and will return only if the specified handle is signaled (thatis, the mutex is not being used by another thread) or if the specifiedtimeout expires. After we obtain the mutex, we perform the necessarysynchronized processing and then call Mutex.ReleaseMutex to release it.

Sometimes we need a mechanism for one threadto notify other threads of some interesting event that occurred. Inthose cases we can use the .NET synchronization event classes,ManualResetEvent and AutoResetEvent. In the world of threadsynchronization, an event is an object that has two states: signaledand nonsignaled. An event has a handle and can be used with WaitHandlejust like a mutex. A thread that waits for an event will be blockeduntil another thread signals the event by calling ManualResetEvent.Setor AutoResetEvent.Set. If we are using a ManualResetEvent, we must callits Reset method to put it back to the nonsignaled state. AnAutoResetEvent will automatically go back to nonsignaled as soon as awaiting thread is notified that the event became signaled.

Conclusion:

That's all it takes to create a multi-threadedapplication in C#.The System.Threading namespace in .NET SDK makesmulti-threading easy.The System.Threading Namespace provides a numberof types that enable multi-threading programming easily in C#. TheThread class in the System.Threading namespace exposes the propertiesand methods to allow the free threading.

Related Articles :

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!