0% found this document useful (0 votes)
9 views

Threading - CSharp Multithreading

This document provides an overview of multithreading in C#. It defines a thread as an execution path of a program, with each thread defining a unique flow of control. Using threads allows an application to perform multiple tasks simultaneously. The life cycle of a thread includes states like unstarted, ready, not runnable, and dead. The first thread created is the main thread. Child threads can be created by extending the Thread class and calling the Start() method. Commonly used properties and methods of the Thread class are also described.

Uploaded by

Siva Vasanthan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Threading - CSharp Multithreading

This document provides an overview of multithreading in C#. It defines a thread as an execution path of a program, with each thread defining a unique flow of control. Using threads allows an application to perform multiple tasks simultaneously. The life cycle of a thread includes states like unstarted, ready, not runnable, and dead. The first thread created is the main thread. Child threads can be created by extending the Thread class and calling the Start() method. Commonly used properties and methods of the Thread class are also described.

Uploaded by

Siva Vasanthan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

C# - MULTITHREADING

http://www.tuto rialspo int.co m/csharp/csharp_multithre ading .htm Co pyrig ht © tuto rials po int.co m

A thread is defined as the execution path of a prog ram. Each thread defines a unique flow of control. If your
application involves complicated and time consuming operations then it is often helpful to set different execution
paths or threads, with each thread performing a particular job.

T hreads are lig htweig ht proc esses. One common example of use of thread is implementation of concurrent
prog ramming by modern operating systems. Use of threads saves wastag e of CPU cycle and increase
efficiency of an application.

So far we have written prog rams where a sing le thread runs as a sing le process which is the running instance of
the application. However, this way the application can perform one job at a time. T o make it execute more than
one task at a time, it could be divided into smaller threads.

Thread Life Cycle


T he life cycle of a thread starts when an object of the System.T hreading .T hread class is created and ends when
the thread is terminated or completes execution.

Following are the various states in the life cycle of a thread:

T he Unstarted State: it is the situation when the instance of the thread is created but the Start method
has not been called.

T he Ready State: it is the situation when the thread is ready to run and waiting CPU cycle.

T he Not Runnable State: a thread is not runnable, when:

Sleep method has been called

Wait method has been called

Blocked by I/O operations

T he Dead State: it is the situation when the thread has completed execution or has been aborted.

The Main Thread


In C#, the System.T hreading .T hread class is used for working with threads. It allows creating and
accessing individual threads in a multithreaded application. T he first thread to be executed in a process is called
the main thread.

When a C# prog ram starts execution, the main thread is automatically created. T he threads created using the
T hread class are called the child threads of the main thread. You can access a thread using the
CurrentT hread property of the T hread class.

T he following prog ram demonstrates main thread execution:

using System;
using System.Threading;

namespace MultithreadingApplication
{
class MainThreadProgram
{
static void Main(string[] args)
{
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
Console.WriteLine("This is {0}", th.Name);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:

This is MainThread

Commonly Used Properties and Methods of the Thread Class


T he following table shows some of the most commonly used properties of the T hread class:

Property Desc ription

CurrentContext Gets the current context in which the thread is executing .

CurrentCulture Gets or sets the culture for the current thread.

CurrentPrinciple Gets or sets the thread's current principal (for role-based security).

CurrentT hread Gets the currently running thread.

CurrentUICulture Gets or sets the current culture used by the Resource Manag er to look up
culture-specific resources at run-time.

ExecutionContext Gets an ExecutionContext object that contains information about the various
contexts of the current thread.

IsAlive Gets a value indicating the execution status of the current thread.

IsBackg round Gets or sets a value indicating whether or not a thread is a backg round thread.

IsT hreadPoolT hread Gets a value indicating whether or not a thread belong s to the manag ed thread
pool.

Manag edT hreadId Gets a unique identifier for the current manag ed thread.

Name Gets or sets the name of the thread.

Priority Gets or sets a value indicating the scheduling priority of a thread.

T hreadState Gets a value containing the states of the current thread.

T he following table shows some of the most commonly used methods of the T hread class:

S.N Method Name & Desc ription

1 public void Abort()


Raises a T hreadAbortException in the thread on which it is invoked, to beg in the process of
terminating the thread. Calling this method usually terminates the thread.

2 public static Loc alDataStoreSlot Alloc ateDataSlot()


Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked
with the T hreadStaticAttribute attribute instead.

3 public static Loc alDataStoreSlot Alloc ateNamedDataSlot( string name)


Allocates a named data slot on all threads. For better performance, use fields that are marked with the
T hreadStaticAttribute attribute instead.

4 public static void Beg inCritic alReg ion()


Notifies a host that execution is about to enter a reg ion of code in which the effects of a thread abort or
unhandled exception mig ht jeopardize other tasks in the application domain.
5 public static void Beg inT hreadAffinity()
Notifies a host that manag ed code is about to execute instructions that depend on the identity of the
current physical operating system thread.

6 public static void EndCritic alReg ion()


Notifies a host that execution is about to enter a reg ion of code in which the effects of a thread abort or
unhandled exception are limited to the current task.

7 public static void EndT hreadAffinity()


Notifies a host that manag ed code has finished executing instructions that depend on the identity of the
current physical operating system thread.

8 public static void FreeNamedDataSlot(string name)


Eliminates the association between a name and a slot, for all threads in the process. For better
performance, use fields that are marked with the T hreadStaticAttribute attribute instead.

9 public static O bjec t GetData( Loc alDataStoreSlot slot )


Retrieves the value from the specified slot on the current thread, within the current thread's current
domain. For better performance, use fields that are marked with the T hreadStaticAttribute attribute
instead.

10 public static AppDomain GetDomain()


Returns the current domain in which the current thread is running .

11 public static AppDomain GetDomain()


Returns a unique application domain identifier

12 public static Loc alDataStoreSlot GetNamedDataSlot( string name )


Looks up a named data slot. For better performance, use fields that are marked with the
T hreadStaticAttribute attribute instead.

13 public void Interrupt()


Interrupts a thread that is in the WaitSleepJoin thread state.

14 public void J oin()


Blocks the calling thread until a thread terminates, while continuing to perform standard COM and
SendMessag e pumping . T his method has different overloaded forms.

15 public static void MemoryBarrier()


Synchronizes memory access as follows: T he processor executing the current thread cannot reorder
instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after
memory accesses that follow the call to MemoryBarrier.

16 public static void ResetAbort()


Cancels an Abort requested for the current thread.

17 public static void SetData( Loc alDataStoreSlot slot, O bjec t data )


Sets the data in the specified slot on the currently running thread, for that thread's current domain. For
better performance, use fields marked with the T hreadStaticAttribute attribute instead.

18 public void Start()


Starts a thread.

19 public static void Sleep( int millisec ondsT imeout )


Makes the thread pause for a period of time.

20 public static void SpinWait( int iterations )


Causes a thread to wait the number of times defined by the iterations parameter

21 public static byte VolatileRead( ref byte address )


public static double VolatileRead( ref double address )
public static int VolatileRead( ref int address )
public static O bjec t VolatileRead( ref O bjec t address )
Reads the value of a field. T he value is the latest written by any processor in a computer, reg ardless of
the number of processors or the state of processor cache. T his method has different overloaded
forms. Only some are g iven above.

22 public static void VolatileWrite( ref byte address, byte value )


public static void VolatileWrite( ref double address, double value )
public static void VolatileWrite( ref int address, int value )
public static void VolatileWrite( ref O bjec t address, O bjec t value )
Writes a value to a field immediately, so that the value is visible to all processors in the computer. T his
method has different overloaded forms. Only some are g iven above.

23 public static bool Yield()


Causes the calling thread to yield execution to another thread that is ready to run on the current
processor. T he operating system selects the thread to yield to.

Creating Threads
T hreads are created by extending the T hread class. T he extended T hread class then calls the Start() method
to beg in the child thread execution.

T he following prog ram demonstrates the concept:

using System;
using System.Threading;

namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
}

static void Main(string[] args)


{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:

In Main: Creating the Child thread


Child thread starts

Manag ing Threads


T he T hread class provides various methods for manag ing threads.

T he following example demonstrates the use of the sleep() method for making a thread pause for a specific
period of time.

using System;
using System.Threading;

namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
// the thread is paused for 5000 milliseconds
int sleepfor = 5000;
Console.WriteLine("Child Thread Paused for {0} seconds",
sleepfor / 1000);
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}

static void Main(string[] args)


{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:

In Main: Creating the Child thread


Child thread starts
Child Thread Paused for 5 seconds
Child thread resumes

Destroying Threads
T he Abort() method is used for destroying threads.

T he runtime aborts the thread by throwing a T hreadAbortExc eption. T his exception cannot be caug ht, the
control is sent to the finally block, if any.

T he following prog ram illustrates this:

using System;
using System.Threading;

namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
try
{

Console.WriteLine("Child thread starts");


// do some work, like counting to 10
for (int counter = 0; counter <= 10; counter++)
{
Thread.Sleep(500);
Console.WriteLine(counter);
}
Console.WriteLine("Child Thread Completed");

}
catch (ThreadAbortException e)
{
Console.WriteLine("Thread Abort Exception");
}
finally
{
Console.WriteLine("Couldn't catch the Thread Exception");
}

static void Main(string[] args)


{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
//stop the main thread for some time
Thread.Sleep(2000);
//now abort the child
Console.WriteLine("In Main: Aborting the Child thread");
childThread.Abort();
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:

In Main: Creating the Child thread


Child thread starts
0
1
2
In Main: Aborting the Child thread
Thread Abort Exception
Couldn't catch the Thread Exception

You might also like