Multithreading- C# FOR BEGINNERS CRASH COURSE (2014)

C# FOR BEGINNERS CRASH COURSE (2014)

Chapter 14 Multithreading

14.1 Thread in C#

A thread defines a control flow. Thread is a basic unit to which the operating system allocates a thread. The execution of a thread is independent within a program.

A single process is executed using one thread. Such process is known as single – threaded process. Only one task can be performed at a time. The user has to wait for the task to complete before executing new task.

For executing more than one thread at a time, multiple threads are created. The process creating two or more threads is known as multithreading.

14.2 Life cycle of a thread

The life cycle of a thread starts when the object of System.Threading.Thread class is created. The life ends as soon as the task is completed. There are various states in the life cycle of a thread.

· Unstarted State: When the instance of the Thread class is created, the thread enters in unstarted state.

· Ready State: The thread is in this state till the program calls the Start() method.

· Not Runnable State: A thread is not in the runnable state if:

1. Waiting: The Wait() method is called to make the thread for a specified condition

2. Blocked: The thread is blocked by an I/O operation

3. Sleeping: The Sleep() method is called to put the thread in sleeping mode.

· Dead State: Once the thread completes its execution or aborted, it is placed in a dead state

14.3 Main thread

The System.Threading.Thread class is used for working with threads. The main thread is created as soon as program starts execution. The Thread class is used for creating threads. They are known as child threads. The user can access the main thread by using the CurrentThread property of the Thread class.

Example:

Example 53:

using System;

namespace thread

{

class MainThread

{

static void Main(string[] args)

{

Thread t1 = new Thread();

t1.Name="Thread1";

Console.WriteLine("Thread is:{0}",t1.Name);

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

Thread is: Thread1

14.4 Properties and methods of the Thread class

Properties:

· IsAlive: The value showing the execution status of the current thread

· CurrentThread: The current running thread is retrieved

· CurrentContext: The current context in which the thread is executing is retrieved

· ExecutionContext: The ExecutionContext object contains information about different contexts

· Name: Gets or sets name of the thread

· ThreadState: The value containing states of the current thread

· Priority: It gets or sets the value showing the scheduling priority of a thread

Methods:

· public static void BeginThreadAffinity(): The host is to about to execute instructions depending on the current physical operating system thread.

· public void Abort(): The ThreadAbortException is raised in thread on which it is invoked.

· public void interrupt(): The thread present in the WaitSleepJoin state is interrupted

· public static AppDomain GetDomain(): A unique domain identifier is returned

· public static void MemoryBarrier(): The processor executes the current thread. The instructions cannot be reordered.

· public void Start(): It starts the thread

· public static bool Yield(): The calling thread to yield execution to another thread which is ready to run on the processor

14.5 Creating and managing threads

The extended thread class creates a thread. The extended thread class calls the Start() method to start the child thread execution.

Example:

Example 54:

using System;

using System.Threading;

namespace MultipleThread

{

class ThreadProgram

{

public static void CallChild()

{

Console.WriteLine("Start child thread");

}

static void Main(string[] args)

{

ThreadStart child1 = new ThreadStart(CallChild);

Console.WriteLine("Creating child thread");

Thread child2 = new Thread(child1);

child2.Start();

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

Start child thread

Creating child thread

Managing Threads

When there is a need to pause a thread for a period of time so that another thread can execute, the Thread.Sleep() method is used. The method takes a single argument stating time in milliseconds.

Example:

Example 55:

using System;

using System.Threading;

namespace Multithreaded

{

class Program

{

public static void ChildThread()

{

Console.WriteLine("Start child thread");

int sleeptime = 4000;

Console.WriteLine("Thread sleeping for {0} seconds",sleeptime / 1000);

Thread.Sleep(sleeptime);

Console.WriteLine("Resume child thread");

}

public static void Main()

{

ThreadStart t1 = new ThreadStart(ChildThread);

Console.WriteLine("child thread created");

Thread child1 = new Thread(t1);

child1.Start();

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

Start child thread

Thread sleeping for 4 seconds

Resume child thread

child thread created

14.6 Destroying threads

The Thread.Abort() method is used to destroy the thread. The ThreadAbortException is thrown when the thread is destroyed. The exception is not caught and is sent to the finally block.

Example:

Example 56:

using System;

using System.Threading;

namespace ThreadDemo

{

class Program

{

public static void ChildThread()

{

try

{

Console.WriteLine("Child Thread started");

for(int j = 0; j < = 10; j ++)

{

Thread.Sleep(1000);

Console.WriteLine("Child thread finished");

}

}

catch(ThreadAbortException e)

{

Console.WriteLine("Exception caught");

}

finally

{

Console.WriteLine("Exception is not handled");

}

}

public static void Main()

{

ThreadStart t1 = new ThreadStart(ChildThread);

Console.WriteLine("Creating child thread");

Thread t2 = new Thread(t1);

t1.Start();

//main thread is stopped

Thread.Sleep(2000);

//child thread aborted

Console.WriteLine("Aborting child thread");

t2.Abort();

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

Creating child thread

Child Thread started

0

1

Aborting child thread

Exception caught

Exception is not handled


Reference links on C#

User can get more detailed information about the C# language using the following reference links.

· Visual Studio Application – The IDE for creating C# applications.

· C# ( Programming guide ) – An overview of C# programming language

· C# Programming – The information about the C# features using .NET framework is explained

· Mono – Cross platform applications can be easily created using the software.

· C# Complete tutorial – It contains lessons useful for beginners to learn C# language


Conclusion

This brings us to the end of this book. We hope that this guide has been thoroughly comprehensible and easy for you to understand and follow. The book should not end your journey on the road to learning C#, instead it should only serve as the beginning. There is a vast amount of information that you can learn on C# therefore once you are done with this book, explore further boundaries of C#.

C# has a growing popularity and is steadily being used more and more. Many famous sites and enterprise level applications are powered by C#. You can find C# in the scientific computing being run on supercomputers. System administration tasks such as package management and configuration use C# as well. No matter what your programming interests, the possibilities for learning, exploring, and growing are endless.

Uploaded by .X0RN. {Zer07} [BЯ]