0% found this document useful (0 votes)
24 views56 pages

Unit 3 - DOT - NET - CORE

Uploaded by

thirosul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views56 pages

Unit 3 - DOT - NET - CORE

Uploaded by

thirosul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Shriram Institute of Information Technology, Paniv

Unit – III
Threading, Exception and Resource Management
Error –
Error is an illegal operation performed by the user which results in abnormal working of the program.
Types of Error –
Errors may be broadly classified into two categories:-

1) Compile time errors

2) Run Time errors

1) Compile time errors:-


All syntax errors will be detected and displayed by the C# compiler and therefore these errors are
known as compile time error.

Whenever the compiler displays an error, it will not create the .exe file. It is therefore necessary that fix
all the error before we can successfully compile and run the program.

The C# compiler does a nice job of telling us where the errors are in the program. Most of the compile time
errors are due to typing mistakes.

The most common problems are:

a) Missing semicolons.
b) Missing of identifiers in classes & methods.
c) Misspelling of identifiers & keywords.
d) Missing double quotes in strings.
e) Use of undeclared variables.
f) Use of = in place == operator

2) Run time errors:-


Sometimes, a program may compile successfully creating the .exe file but may not run properly. Such
programs may produce wrong results due to wrong logic or may terminate due to errors, such as stack
overflow.

Most common run time errors are:

a) Dividing an integer by zero.


b) Accessing an element that is out of the bounds of an array.
c) Trying to store a value into an array of an incompatible class or type.
d) Attempting to use a negative size for an array.
e) Converting an invalid string to a number or vice versa & so on.

When such errors are encountered, C# typically generates an error message and aborts the program

Prof. Honrao Bhagyashri Prakash (1 )


Shriram Institute of Information Technology, Paniv

What is Exception:-
An exception is a condition that is caused by a run time error in a program. In other word, an exception
is an error that occurs at run time.

When the C# compiler encounters an error such as dividing an integer by zero, it creates an exception
object and throws it (i.e. informs us that an error has occurred).

If the exception object is not caught and handled properly, the compiler will display an error message &
will terminate the program.

If we want the program to continue with the execution of the remaining code, then we should try to
catch the exception object thrown by the error condition & then display an appropriate message for taking
corrective actions. This task is known as “Exception Handling”.

The mechanism suggests incorporation of a separate error handling code that performs the following
tasks.

a) Find the problems (Hit the exception).


b) Inform that an error has occurred (Throw the exception).
c) Receive the error information (catch the exception).
d) Take corrective actions (Handle the exception).

The System.Exception Class:-


In C#, exceptions are represented by classes. All exception classes must be derived from the built-in
exception class Exception, which is part of System namespace. Thus, all exceptions are subclasses of
Exception class.

One very important subclass of Exception is System.Exception. This is exception class from which all
exceptions generated by the C# runtime system (CLR) are derived.

The .NET framework defines several built in exceptions that are derived from System.Exception class.

Common C# exceptions are:

1) ArgumentException:- An argument to a method was invalid.

2) ArithmeticException:- Arithmetic over or underflow has occurred.

3) DivideByZeroException:- It is derived from Arithmetic Exception. An attempt was made to divide by


zero.

4) IndexOutOfRangeException:- An array index is out of bounds.

5) StackOverFlowException:- Occur when a stack has overflowed.

Prof. Honrao Bhagyashri Prakash (2 )


Shriram Institute of Information Technology, Paniv

6) OutOfMemoryException:- Occur when Not enough memory to continue execution.

7) NullReferenceException:- Attempt to use an unassigned reference.

8) InvalidCastException:- An attempt was made to cast an invalid class.

9) NotFiniteNumberException:- A number is not valid

10) NotSupportedException:- Indicates that, a method is not implemented by a class.

11) InvalidOperationException:- A method was called at an invalid time.

Exception Handling Fundamentals:-


A C# exception is an object that describes an error condition that has occurred in a program. When an
exceptional condition arises, an object representing that exception is created and thrown.

C# exception handling is managed via four keywords: try, catch, throw, and finally.

The statement in a program may raise exception are placed within a try block. If an exception occurs
within the try block, it is thrown.

The catch block in program catch this exception and handle it in some rational manner. System
generated exceptions are automatically thrown by the CLR. To manually throw an exception, use the keyword
throw.

Any code that absolutely must be executed before a method returns is put in a finally block.

The basic concepts of exception handling are throwing an exception & catching it.

Syntax for exception handling


try
{
// Block of code to monitor for errors.
}
catch (ExceptionType obj)
{
// Exception handler
}
finally
{
// Block of code to be executed before try block ends
}

Prof. Honrao Bhagyashri Prakash (3 )


Shriram Institute of Information Technology, Paniv

try Block

Statement that causes an Exception Object Creator


exception
Throws
Exception
Object

Catch Block

Statements that handle Exception Handler


the exception

Fig.:- Exception Handling Mechanism

a) try Block:-
The try block can have one or more statements that could generate an exception. If anyone statement
generates an exception, the remaining statements in the block are skipped and execution jumps to the catch
block that is placed next to the try block.

The try block start with the keyword try. A try block should have one or more catch blocks or one
finally block or both. If neither is present, a compiler error occurs, which say‟s try without „catch‟ or „finally‟.

b) Catch block:-
A catch block can have one or more statements that are necessary to process the exception.

The catch statement works like a method definition. The catch statement is passed a single parameter,
which is the reference to the exception object thrown by the try block. If the catch parameter matches with
the type of exception object, then the exception is caught and statements in the catch block will be
executed. Otherwise the exception is not caught and the default exception handler will cause the execution to
terminate.
Program:
using System;
namespace Programm
{
class sample
{
int a, b, c;

Prof. Honrao Bhagyashri Prakash (4 )


Shriram Institute of Information Technology, Paniv

public int result()


{
try
{
Console.Write("Enter first Number: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second Number: ");
b = Convert.ToInt32(Console.ReadLine());
c = a / b;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Attempting to divide by zero");
}
return c;
}
}
class Program
{
static void Main(string[] args)
{
int r;
sample s = new sample();
r = s.result();
Console.WriteLine("Result is: " + r);
Console.ReadLine();
}
}
}

Output –
Enter first Number: 10

Enter second Number: 0

Attempting to divide by zero

Result is: 0

Prof. Honrao Bhagyashri Prakash (5 )


Shriram Institute of Information Technology, Paniv

throw Keyword:-
An exception can be caught only if it is defined or in other word, thrown. If we cannot throw an
exception manually then C# run-time system throws exception automatically.

However, it is possible to manually throw an exception by using the throw statement.

The general form of throw is:

throw exceptionobject;

Here, exception object must be an instance of an exception class derived from Exception.

The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.

Program -

using System;
namespace operatoroverload
{
class sample
{
int a, b, c;
public sample(int x, int y)
{
a = x;
b = y;
}
public void calculate()
{
try
{
if (b == 0)
throw new DivideByZeroException("Division Error....");
c = a / b;
Console.WriteLine("Result: " + c);
}
catch (DivideByZeroException e)
{
Console.WriteLine(e.Message);
}

Prof. Honrao Bhagyashri Prakash (6 )


Shriram Institute of Information Technology, Paniv

}
}
class Program
{
static void Main(string[] args)
{
int x, y;
Console.Write("Enter 1st Number: ");
x = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter 2nd Number: ");
y = Convert.ToInt32(Console.ReadLine());
sample s = new sample(x, y);
s.calculate();
Console.Read();
}
}
}

Output -
Enter 1st Number : 5

Enter 2nd number: 0

Division Error....

Multiple Catch Statement:-


In some cases, more than one exception could be raised by a single try block. To handle this type of
situation, we can specify two or more catch clauses, each catching a different type of exception. When
an exception is thrown, each catch statement is inspected in order, and the first one whose type matches
that of the exception is executed.
After one catch statement executes, the others are by passed and execution continues after the try/ catch
block.
Program Using multiple catch statements:-
using System;
namespace MultipalCatch
{
class Sample

Prof. Honrao Bhagyashri Prakash (7 )


Shriram Institute of Information Technology, Paniv

{
int a = 10, b = 5, c = 5;
int[] arr = new int[] { 10, 20, 30, 40 };
int sum, result;
public void calcutate()
{
try
{
result = a / (b - c);
Console.WriteLine("Result:" + result);
arr[5] = 50;
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
catch (DivideByZeroException e)
{
Console.WriteLine("Attempt to divide by Zero...");
}
catch (ArithmeticException e)
{
Console.WriteLine(e.Message);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();

Prof. Honrao Bhagyashri Prakash (8 )


Shriram Institute of Information Technology, Paniv

s.calcutate();
Console.Read();
}
}
}
Output:
Attempt to divide by Zero...

Finally Statement:-
By using finally block, we can clean up any resources that we are allocated in a try block, and we can
run code even if an exception occurs in the try block.

Finally creates a block of code that will be executed after a try/ catch blocks has completed and before
the code following the try / catch block.

The finally block will execute whether or not an exception is thrown. If an exception is thrown, the
finally block will execute even if no catch statement matches the exception.

Generally, finally block is used to close the files that have been opened, connections to the database that
have been opened, sockets in the network that have been opened or for releasing an system resources.

The finally clause is optional. However, each try statement requires at least one catch or a finally
clause.

Syntax of finally block:


try
{
// Statements
------------
------------
}
finally
{
// Statements
------------
------------
}
Or

try
{
// Statements
------------
------------
}
catch ( ------- )
{

Prof. Honrao Bhagyashri Prakash (9 )


Shriram Institute of Information Technology, Paniv

// Statements
------------
------------
}
finally
{
// Statements
------------
------------
}

Program 1 Using finally statement:-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FinallyDemo
{
class Program
{
static void Main(string[] args)
{
FileStream fs = File.Open("c:\\abc.txt", FileMode.Append,
FileAccess.Write);
BinaryWriter w = new BinaryWriter(fs);
try
{
w.Write('a');
w.Write(“Paniv");
w.Write(1234);
w.Write(23.66);
w.Write(" College");
w.Close();
fs.Close();
Console.WriteLine("File is created and write successful ...");
}

Prof. Honrao Bhagyashri Prakash (10 )


Shriram Institute of Information Technology, Paniv

catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
w.Close();
fs.Close();
Console.WriteLine("Finally Block is Executed .....");
}
Console.Read();
}
}
}
Output:

File is created and write successful...

Finally Block is Executed .....

Program 2 Using finally statement:-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FinallyDemo
{
class Program
{
static void Main(string[] args)
{
int number = 4;
int divisor = 0;
try
{
int output = number / divisor;
}
catch (DivideByZeroException)

Prof. Honrao Bhagyashri Prakash (11 )


Shriram Institute of Information Technology, Paniv

Console.WriteLine("Not possible to divide by zero!");


}
finally
{

Console.WriteLine("Finally Block!");
}
Console.Read();
}
}
}
Output:-

Not possible to divide by zero!


Finally Block!

Custom Exception in C#
 Although the .NET framework contains all kinds of exception types which are sufficient in most
cases, it can make sense to define custom exceptions in your own applications. They can greatly
simplify and improve the error handling and thus increase the overall code quality. Generally, for large
scale projects (i.e. having multiple modules talks to each other), one should define custom exceptions.
 For Implementing Custom Exception Handling, we need to derive the class CustomException from the
system Base Class ApplicationException.
 Any Custom Exception you create needs to derive from the System.Exception class. You can either
derive directly from it or use an intermediate exception like SystemException or ApplicationException
as base class.
Steps to Create Custom Exception
1) Implement error handling in the user interface.
2) Create and implement custom error messages.
3) Create and implement custom error handlers.
4) Raise and handle errors.

Program :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2

Prof. Honrao Bhagyashri Prakash (12 )


Shriram Institute of Information Technology, Paniv

{
class MyException : ApplicationException
{
public void MyException()
{
Console.WriteLine("An exception occurred ");
}
public void MyDivideException()
{
Console.WriteLine("Exception occured, divisor should not be zero");
}
}
class TestMyException
{
public static void Main(String[] arg)
{
int d, div, res;
Console.Write("Enter Integer Number:");
d = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Divisor:");
div = Convert.ToInt32 (Console.ReadLine());
try
{
if (div == 0)
{
throw new MyException();
}
}
catch (MyException e)
{
e.MyDivideException();
}
res = d / div;
Console.WriteLine("Result:{0}", res);
Console.Read();
}
}
}

Output: -
Enter Integer Number:12
Enter Divisor:0
Exception occurred, divisor should not be zero

Prof. Honrao Bhagyashri Prakash (13 )


Shriram Institute of Information Technology, Paniv

Threading
Introduction –
C# have many features, one it‟s most powerful is its built in support for multithreading
programming. A multithreading program contains two or more parts that can run currently. Each part of such
program is called as thread and each thread defines a separate path execution. Thus multithreading is a
specialized from of multitasking. There are two distinct types of multitasking that is –
a) Process based.
b) Thread based.

a) Process Based –
A process is in essence a program that is executing thus, process based multitasking is the feature that
allows your computer to run two or more process program concurrently.
Example – It is process based multitasking that allows you to run a word processor at the same time you are
using a spreadsheet or browsing internet.
In process based multitasking a program is the smallest unit of code that can be dispatched by schedule.

b) Thread Based –
A thread is a dispatched able unit of executable code. In thread based multithreading environment all
process has at least one thread, but they can have more. This means that a single program can perform two or
more tasks at once.

The difference between process based and thread based multithreading is –


 Process based multitasking handles the concurrent execution of program.
 Thread based multitasking deals with the concurrent execution of pieces of the same program.

The multithreading classes and interfaces contained in the System.Threading namespace. We can use
methods and properties contained in these classes to perform task such as synchronizing the activities of a
thread and creating a thread.

 Properties –
1) CurrentThread – it display the current running thread name.
2) IsAlive – it used to retrieve a value to indicate the current status of thread execution. The value of
IsAlive property is true if the thread has been started, otherwise the value is false.
3) IsThreadPoolThread – To retrieve a value to indicate whether a thread is part of thread pool or not.

Prof. Honrao Bhagyashri Prakash (14 )


Shriram Institute of Information Technology, Paniv

4) Name – it used to specify the name for thread.


5) Priority –Gets or Sets a value which indicates the scheduling priority of thread. By default the value of
the priority is Normal. We can assign Highest, AboveNormal, Normal, BelowNoraml or Lowest.
6) ThreadState – To retrieve a value which indicates the state of a thread? By default the value of
ThreadState property is Unstarted. These values can be Running, Stopped, Suspended, Unstarted or
WaitSleepJoin

 Methods –
1) Abort () – This method is used to terminate the thread.
2) Interrupt () – Interrupt the thread that is in the WaitSleepJoin thread state.
3) Join () –Blocks the thread until a thread terminated.
4) ResetAbort () – Cancels an Abort requested for the current thread.
5) Start () – It used to start the thread.
6) Sleep (int millisecond TimeOut) – it used to make the thread pause for a period of time.
7) SpinWait (int iteration) – it used to causes a thread to wait the number of times defined by the
iterations parameters.

Thread Life Cycle –


The life cycle of thread starts when an object of the System.Threading. Thread class is created and ends
when thread us terminated or completed execution.
Following are the various states in the Life Cycle of a thread.
1) Unstarted State – It is situation when the instance of the thread is created but the start method has not
been called.
2) Ready State – It is situation when the thread is ready to run and writing CPU cycle.
3) Not Runnable State – A thread is not Runnable, when –
a. Sleep method has been called.
b. Wait method has been called.
c. Blocked by I/O operation.

4) Dead State – It is situation when thread has completed execution or has been aborted.

In C# the System.Threading.Thread class is used for working with threads. It allow creating and
accessing individual threads in a multithreading application. The first thread executed in the process is called as
main thread.

Prof. Honrao Bhagyashri Prakash (15 )


Shriram Institute of Information Technology, Paniv

When a C# program starts execution the main thread is automatically created. The threads created using
the Thread class are called the child threads of main thread. You can access thread using CurrentThread
Property of thread class.
Example –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace readonlyExample
{
class Program
{
static void Main(string[] args)
{
Thread th = Thread.CurrentThread;
th.Name = "Main thread";
Console.WriteLine("This is {0} ", th.Name);
Console.ReadLine();
}
}
}
Output -
This is Main Thread

Creating Thread Class –


Threads are created by extending the thread class. The extended thread class then calls the Start()
methods to begin the child thread execution.
Example –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

Prof. Honrao Bhagyashri Prakash (16 )


Shriram Institute of Information Technology, Paniv

namespace readonlyExample
{
class Program
{
public static void CallThread()
{
Console.WriteLine("Child Thread Start");
}
static void Main(string[] args)
{
ThreadStart ch = new ThreadStart(CallThread);
Console.WriteLine("In main, creating the child thread");
Thread chthread = new Thread(ch);
chthread.Start();
Console.ReadLine();
}
}
}
Output –
In main, creating the child thread
Child Thread Start

Thread Priority –
Each thread has a priority setting associated with thread. A threads priority determines how much CPU
time a thread receives relative to other currently executing threads. In general low priority threads receive little
CPU time and high priority receive lots of CPU time.
In C# threads can be scheduled by setting the priority of the thread using the Priority property of thread
class. The C# provide the following values for the priority property of a specific thread –
1) Highest
2) Lowest
3) Normal
4) BelowNormal
5) AboveNormal

Prof. Honrao Bhagyashri Prakash (17 )


Shriram Institute of Information Technology, Paniv

The general formula of priority –


public ThreadPriority.Lowest;
Example –
To set the priority th thread as Lowest, we can use the code –
th.Priority = ThreadPriority.Lowest;

Example –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace readonlyExample
{
class Program
{
public void ThreadFirst()
{
Console.WriteLine("\nWelcome in C# World");
}
public void ThreadSecond()
{
Console.WriteLine("\nThank you to use C#");
}
static void Main(string[] args)
{
Program p = new Program();
Thread t1=new Thread(new ThreadStart(p.ThreadFirst));
t1.Priority = ThreadPriority. Lowest;
t1.Start();
Thread t2 = new Thread(new ThreadStart(p.ThreadSecond));
t2.Priority = ThreadPriority.Highest;
t2.Start();

Prof. Honrao Bhagyashri Prakash (18 )


Shriram Institute of Information Technology, Paniv

Console.ReadLine();
}
}
}

Output –
Thank you to use C#
Welcome in C# World

Types of Tread –
In C#, there are two types of threads: foreground threads and background threads.

1) Foreground Threads: These threads are created using the Thread class in C# and are considered to be the
main threads of an application. They prevent the application from terminating until all foreground threads
have completed their tasks. A foreground thread can be created by calling the Thread.Start() method.
2) Background Threads: These threads are also created using the Thread class in C#, but they are considered
to be the secondary threads of an application. They do not prevent the application from terminating, even if
they are still running. A background thread can be created by calling the Thread.Start() method and then
setting the IsBackground property of the thread to true before starting it.
 When an application starts, it automatically creates a foreground thread, which is the main thread of the
application. All the threads are background thread by default. However, you can change the type of a
thread by setting the IsBackground property of the thread.

 Foreground threads are useful when you need to perform a task that is critical to the operation of the
application and must be completed before the application can terminate. For example, a foreground
thread might be used to update the user interface or to perform important calculations.
 Background threads are useful when you need to perform a task that is not critical to the operation of the
application and can be terminated if the application needs to shut down. For example, a background
thread might be used to download a large file or to perform periodic updates to a database.
 It is important to note that a background thread can be terminated at any time if the application needs to
shut down. Therefore, you should be careful when using background threads and ensure that they are not
performing critical tasks that could cause the application to malfunction if they are terminated abruptly.
 Multi-threading is the most useful feature of C# which allows concurrent programming of two or more
parts of the program for maximizing the utilization of the CPU. Each part of a program is called Thread.

Prof. Honrao Bhagyashri Prakash (19 )


Shriram Institute of Information Technology, Paniv

So, in other words, threads are lightweight processes within a process. C# supports two types of threads
are as follows :
1) Foreground Thread
A thread which keeps on running to complete its work even if the Main thread leaves its
process, this type of thread is known as foreground thread. Foreground thread does not care whether the
main thread is alive or not, it completes only when it finishes its assigned work. Or in other words, the
life of the foreground thread does not depend upon the main thread.
Example:

using System;
using System.Threading;

class GFG
{

static void Main(string[] args)


{

Thread thr = new Thread(mythread);


thr.Start();
Console.WriteLine("Main Thread Ends!!");
}
static void mythread()
{
for (int c = 0; c <= 3; c++)
{

Console.WriteLine("mythread is in progress!!");
Thread.Sleep(1000);

}
Console.WriteLine("mythread ends!!");
Console.ReadLine();
}
}

Output: -
Main Thread Ends!!
mythread is in progress!!
mythread is in progress!!
mythread is in progress!!
mythread is in progress!!
mythread ends!!

Prof. Honrao Bhagyashri Prakash (20 )


Shriram Institute of Information Technology, Paniv

Explanation: In the above example, thr thread runs after main thread ended. So, the life of thr thread doesn‟t
depend upon the life of the main thread. The thr thread only ends its process when it completes its assigned task.

2) Background Thread
A thread which leaves its process when the Main method leaves its process, these types of the
thread are known as the background threads. Or in other words, the life of the background thread
depends upon the life of the main thread. If the main thread finishes its process, then background thread
also ends its process.
Note: If you want to use a background thread in your program, then set the value of IsBackground
property of the thread to true.
Example:

using System;
using System.Threading;

class GFG
{
static void Main(string[] args)
{
Thread thr = new Thread(mythread);
thr.Name = "Mythread";
thr.Start();
thr.IsBackground = true;
Console.WriteLine("Main Thread Ends!!");
Console.ReadLine();
}
static void mythread()
{
Console.WriteLine("In progress thread is: {0}",Thread.CurrentThread.Name);
Thread.Sleep(2000);
Console.WriteLine("Completed thread is: {0}",Thread.CurrentThread.Name);
}
}
Output: -
Main Thread Ends!!
In progress thread is: Mythread
Completed thread is: Mythread

Explanation: In the above example, IsBackground property of Thread class is used to set the thr thread as a
background thread by making the value of IsBackground true. If you set the value of IsBackground false, then

Prof. Honrao Bhagyashri Prakash (21 )


Shriram Institute of Information Technology, Paniv

the given thread behaves as a foreground Thread. Now, the process of the thr thread ends when the process of
the main thread ends.

Thread Class –
C# multithreading system is built upon the Thread class, which encapsulates a thread of execution. The
thread class is sealed, which means that it cannot be inherited. Thread class help us to perform tasks such as
creating and setting the priority of a thread. We can use this class to control a thread and obtain its status.
A thread is defined as execution path of a program. 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 path or thread, with each thread performing a particular job.
Thread class provides various properties that allow us to perform such as obtaining the status of thread
and specifying a name for thread.

Multithreading-
C# is a multi-paradigm programming language that supports several programming styles,
including procedural, object-oriented, and functional programming. One of the essential features of C# is its
support for multithreading, which enables developers to write applications that can perform multiple tasks
concurrently. Use multithreading when your application has tasks that can run concurrently, independently,
and without needing to be sequentially organized. This is particularly useful when performing I/O-bound work
or expensive computations while keeping the user interface responsive.
Implementing multithreading in C# requires a step further. You create more instances of the
Thread class, one for each task you want to run concurrently:
Example-
using System;
using System.Threading;
namespace LockDemo
{
class Program
{
public static void show1()
{
for (int i = 0; i <= 5; i++)
{
Console.WriteLine("Show1 thread is started...");

Prof. Honrao Bhagyashri Prakash (22 )


Shriram Institute of Information Technology, Paniv

Thread.Sleep(500);
}
}
public static void show2()
{
for (int j = 0; j <= 5; j++)
{
Console.WriteLine("Show2 thread is started...");
Thread.Sleep(500);
}
}

public static void Main(String[] args)


{
Thread t1 = new Thread(show1);
Thread t2 = new Thread(show2);
t1.Start();
t2.Start();
Console.ReadLine();
}
}
}
Output-
Show1 thread is started...
Show2 thread is started...
Show1 thread is started...
Show2 thread is started...
Show1 thread is started...
Show2 thread is started...
Show1 thread is started...
Show2 thread is started...
Show1 thread is started...
Show2 thread is started...
Show1 thread is started...
Show2 thread is started...

Prof. Honrao Bhagyashri Prakash (23 )


Shriram Institute of Information Technology, Paniv

Synchronization –
When using multiple threads you will sometimes need to coordinate the activities of two or more of
threads. The process by which this is achieved is called as Synchronization.
The most common reason for using synchronization is when two or more threads need access to a shared
resource that can be used by only one thread at a time.
Example – when one thread is writing to a file, a second thread must be prevented from doing at the same time.
Another situation in which synchronization is needed is when one thread is waiting for an event that is
caused by another thread. In this case there must be some means by which the first thread is held in a suspended
state until the event has occurred. Then the waiting thread must resume execution.
Key to synchronization is the concept of a lock, which controls access to a block of code within object.
When an object is locked by one thread, no other thread can gain access to the locked block of code. When
thread releases the lock, the code block is available for use by another thread.
The lock feature is built into the C# language. Thus all objects can be synchronized. Synchronization is
supported by the keyword lock. The general form of lock is –
lock (object)
{
//statement to be synchronized;
}
Example –
using System;
using System.Threading;
namespace LockDemo
{
class LockDisplay
{
public void DisplayNum()
{
lock (this)
{
for (int i = 1; i <= 5; i++)
{
Thread.Sleep(500);
Console.WriteLine("i = {0}", i);
}

Prof. Honrao Bhagyashri Prakash (24 )


Shriram Institute of Information Technology, Paniv

}
}
}
class Example
{
public static void Main(string[] args)
{
LockDisplay obj = new LockDisplay();

Console.WriteLine("Threading using Lock");

Thread t1 = new Thread(new ThreadStart(obj.DisplayNum));


Thread t2 = new Thread(new ThreadStart(obj.DisplayNum));
t1.Start();
t2.Start();
Console.ReadLine();
}
}
}
Output –
Threading using Lock
i=1
i=2
i=3
i=4
i=5
i=1
i=2
i=3
i=4
i=5

Prof. Honrao Bhagyashri Prakash (25 )


Shriram Institute of Information Technology, Paniv

 Generic Collection Classes –


Generic collection in C# is defined in System.Collection.Generic namespace. It provides a generic
implementation of standard data structure like linked lists, stacks, queues, and dictionaries. These collections are
type-safe because they are generic means only those items that are type-compatible with the type of the collection
can be stored in a generic collection, it eliminates accidental type mismatches. Generic collections are defined by
the set of interfaces and classes. Below list contains the generic collection classes –
1) List<T>
2) Dictionary<TKey, TValue>
3) Queue<T>
4) Stack<T>

1) List<T> -
List<T> class represents the list of objects which can be accessed by index. It comes
under the System.Collection.Generic namespace. List class can be used to create a collection of different types
like integers, strings etc. List<T> class also provides the methods to search, sort, and manipulate lists.
It is a dynamic array that provides functionality similar to that found in the non-generic
ArrayList class.
 Characteristics:
 It is different from the arrays. A List<T> can be resized dynamically but arrays cannot.
 List<T> class can accept null as a valid value for reference types and it also allows duplicate elements.
 List<T> class is the generic equivalent of ArrayList class by implementing the IList<T> generic
interface.
 List<T> class is not sorted by default and elements are accessed by zero-based index.

 Methods –
1) Add () – Add () method is used to add object or elements to the end of List.
2) AddRange () - AddRange () Method is used to add the elements of the specified collection to the end of
the List<T>.
3) Clear () - Clear Method is used remove the all the elements from the List.
4) Contains () - Contains() Method is used to check whether an element is in the List<T> or not.
5) Equals () - Equals() Method is used to check if a specified List<T> object is equal to another List<T>
object or not.

Prof. Honrao Bhagyashri Prakash (26 )


Shriram Institute of Information Technology, Paniv

6) Exists () - Exists() Method is used to check whether the List<T> contains elements which match the
conditions defined by the specified predicate.
7) Find () - Find() Method is used to search for an element which matches the conditions defined by the
specified predicate and it returns the first occurrence of that element within the entire List<T>.
8) Insert () – Insert () method is used to insert an elements into the ArrayList at the specified index.
9) Remove () - Remove(T) Method is used to remove the first occurrence of a specific object from the List.
10) RemoveAt () - RemoveAt (Int32) Method is used to remove the element at the specified index of the
List<T>.
11) Reverse () - Reverse Method is used to reverse the order of the elements in the List<T>
12) Sort () - Sort() Method is used to sort the elements or a portion of the elements in the List<T>

 Properties -
1) Count – Count property returns the number of elements actually contained in the List.
2) Capacity – Gets or sets the number of elements that the List can contain.
3) Items – It will return the particular items of specified index.

Example -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<int> mylist = new List<int>();
mylist.Add(20);
mylist.Add(15);
mylist.Add(10);
mylist.Add(50);
mylist.Add(80);
Console.WriteLine("Elements are add into list");
Console.WriteLine("After adding elements list are...");
foreach (int i in mylist)
{
Console.WriteLine(i);

Prof. Honrao Bhagyashri Prakash (27 )


Shriram Institute of Information Technology, Paniv

}
mylist.Insert(3, 45);
Console.WriteLine("After insert element list is");
foreach (int i in mylist)
{
Console.WriteLine(i);
}
mylist.RemoveAt(2);
Console.WriteLine("After removing list is");
foreach (int i in mylist)
{
Console.WriteLine(i);
}
mylist.Reverse();
Console.WriteLine("After reverse method list is");
foreach (int i in mylist)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}

Output –
Elements are add into list
After adding elements list are...
20
15
10
50
80
After insert element list is
20
15
10
45
50
80
After removing list is

Prof. Honrao Bhagyashri Prakash (28 )


Shriram Institute of Information Technology, Paniv

20
15
45
50
80
After reverse method list is
80
50
45
15
20

2) Dictionary<TKey, TValue>
The Dictionary<TKey, TValue> is a generic collection that stores key-value pairs in no particular order. It
stores key/value pairs and provides functionality similar to that found in the non-generic HashTable class.
 Characteristics -
1) Dictionary<TKey, TValue> stores key-value pairs.
2) Comes under System.Collection.Generic namespace.
3) Implements IDictionary<TKey, TValue> interface.
4) Keys must be unique and cannot be null.
5) Values can be null or duplicate.
6) Values can be accessed by passing associated key in the indexer e.g. myDictionary[key]
7) Elements are stored as KeyValuePair<TKey, TValue> objects.

 Methods –

1) Add () – Add () method adds an element with the specified key and value into the Dictionary.

2) Clear () – It used to remove all elements from the Dictionary.

3) ContainsKey () – This method determines whether the Dictionary contains specific key.

4) ContainsValue () - This method determines whether the Dictionary contains specific value.

5) Remove () – This method is used to remove the elements with specified key from the

Dictionary

Prof. Honrao Bhagyashri Prakash (29 )


Shriram Institute of Information Technology, Paniv

 Property –

1) Count – Count property return the number of key and value pair contained in the Dictionary.

2) Item – Gets or sets the value associated with the specified key.

3) Keys – Gets an ICollection containing the keys in the Dictionary.

4) Values - Gets an ICollection containing the values in the Dictionary.

5) IsReadOnly - This property will indicate whether the Dictionary is read only or not.

Example -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Dictionary<int, string> mydir = new Dictionary<int, string>();
mydir.Add(1, "CPP");
mydir.Add(6, "PHP");
mydir.Add(4, "C#");
mydir.Add(8, "ASP");
mydir.Add(9, "JAVA");
mydir.Add(7, "Python");

Console.WriteLine("Elements are inserted");


Console.WriteLine("After adding elements are");
foreach (KeyValuePair<int,string> obj in mydir)
Console.WriteLine(obj.Key + " = "+ obj.Value);

Console.WriteLine("Contians value CPP is : "+mydir.ContainsValue("CPP"));

mydir.Remove(4);
Console.WriteLine("After removing elements are:");
foreach (KeyValuePair<int, string> obj in mydir)
Console.WriteLine(obj.Value);
Console.WriteLine("Dictionary contain elements : " + mydir.Count);
Console.ReadLine();

Prof. Honrao Bhagyashri Prakash (30 )


Shriram Institute of Information Technology, Paniv

}
}
}

Output –
Elements are inserted
After adding elements are
1 = CPP
6 = PHP
4 = C#
8 = ASP
9 = JAVA
7 = Python
Contians value CPP is : True
After removing elements are:
CPP
PHP
ASP
JAVA
Python
Dictionary contain elements : 5

3) Queue<T> -
Queue<T> is a data structure which is based on First in First Out (FIFO) principle. Queue<T>

provides functionality similar to that found in the non-generic Queue class. The element is added

from one end (known as rear end) and removed from other end (known as front end). Queue<T>

processes messages or data sequentially. A queue takes a null reference as a valid value. It can also

take a duplicate value. Queue<T> can also grow dynamically.

The following are the some properties and methods used in a queue class –

 Methods –

1) Enqueue () – The Enqueue () method is used to add an object to the end of the Queue. It takes

a single argument as object type.

2) Dequeue () – The Dequeue () method removes and return the object at beginning of the

Queue.

Prof. Honrao Bhagyashri Prakash (31 )


Shriram Institute of Information Technology, Paniv

3) Contains () - Contains () method is used to check the specified object is present in queue or

not. It return true if object is present in queue otherwise it return false.

4) Clear () - Clear () method is used to removes the entire element from the queue.

 Property –

1) Count - Count Property returns the number of elements contained in queue

Example –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Queue<string> myqueue = new Queue<string>();
myqueue.Enqueue("CPP");
myqueue.Enqueue("PHP");
myqueue.Enqueue("DBMS");
myqueue.Enqueue("Java");
Console.WriteLine("Elements add in Queue");

Console.WriteLine("\nQueue Elements are..");


foreach (object obj in myqueue)
Console.WriteLine(obj.ToString());

Console.WriteLine("\nRemoved element is: " + myqueue.Dequeue());

Console.WriteLine("\nAfter Removing Queue is --");

Prof. Honrao Bhagyashri Prakash (32 )


Shriram Institute of Information Technology, Paniv

foreach (object obj in myqueue)


Console.WriteLine(obj.ToString());

Console.WriteLine("\nQueue contain element: " + myqueue.Contains("Java"));


Console.WriteLine("\nQueue contain {0} number of elements", myqueue.Count);
Console.ReadLine();

}
}
}

Output –
Elements add in Queue
Queue Elements are..
CPP
PHP
DBMS
Java
Removed element is: CPP
After Removing Queue is --
PHP
DBMS
Java

Queue contain element: True


Queue contain 3 number of elements

4) Stack<T> -
Stack<T> class is data structure which is based on Last in First Out (LIFO) principle. It provides
functionality similar to that found in the non-generic Stack class. The element is added to and removed from the
same end of the stack. The mechanism to add an element is known as push and remove an element is known as
pop.
A stack<T> takes a null reference as a valid value. It can also take duplicate value. Stack can grow
dynamically when we add elements in a stack.

Prof. Honrao Bhagyashri Prakash (33 )


Shriram Institute of Information Technology, Paniv

The following are the some properties and methods used in a stack class –
 Methods –
1) Push () – Push () method is used to insert an object on the top of the stack. This method takes single
argument as object.
2) Pop () – This method removes and returns the object from the top of the stack.
3) Peek () – This method returns the object at the top of stack without removing it.
4) Clear () – Clear () method is used to removes the entire element from the stack.
5) Contains () – Contains () method is used to check the specified object is present in stack or not. It return
true if object is present in stack otherwise it return false.
 Property –
1) Count – Count Property returns the number of elements contained in stack.

Example –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Stack<string> mystack = new Stack<string>();
mystack.Push("CPP");
mystack.Push("PHP");
mystack.Push("DBMS");
mystack.Push("Java");
Console.WriteLine("Elements add in stack");

Console.WriteLine("\nStack Elements are..");


foreach (object obj in mystack)
Console.WriteLine(obj.ToString());

Prof. Honrao Bhagyashri Prakash (34 )


Shriram Institute of Information Technology, Paniv

Console.WriteLine("\nRemoved element is: " + mystack.Pop());

Console.WriteLine("\nAfter Removing stack is --");


foreach (object obj in mystack)
Console.WriteLine(obj.ToString());

Console.WriteLine("\nTop most element from stack is: " + mystack.Peek());


Console.WriteLine("\nStack contain element: " + mystack.Contains("Java"));
Console.WriteLine("\nStack contain {0} number of elements", mystack.Count);
Console.ReadLine();
}
}
}

Output –
Elements add in stack
Stack Elements are..
Java
DBMS
PHP
CPP
Removed element is: Java
After Removing stack is --
DBMS
PHP
CPP
Top most elements from stack is: DBMS
Stack contain element: False
Stack contain 3 number of elements

Prof. Honrao Bhagyashri Prakash (35 )


Shriram Institute of Information Technology, Paniv

 Concurrent Collection Classes –


The .NET Framework 4.0 provides new classes for concurrency as Concurrent Collections. The
Concurrent Collections allow us to create type-safe (due to the generic implementation) as well as thread-safe
collections.
These collection classes are specifically used in multithreading. These collections can be
accessed by multiple threads at a time hence they are called Concurrent collections. They allow us to share the
data between several threads with thread safety. They are available under the namespace
System.Collections.Concurrent. Below are the different types of concurrent collections.
1) ConcurrentDictionary< Key, Value>: Thread-safe version of Generic Dictionary.
2) ConcurrentQueue<T>: Thread-safe version of the generic queue (FIFO Data Structure).
3) ConcurrentStact<T>: Thread-safe version of generic stack (LIFO Data Structure).
4) ConcurrentBag<T>: Thread-safe implementation of an unordered collection.
5) BlockingCollection<T>: Provides a Classical Producer-Consumer pattern.

1) ConcurrentDictionary< Key, Value>: Thread-safe version of Generic Dictionary:-


The ConcurrentDictionary<TKey, TValue> represents a thread-safe collection of key/value pairs
that can be accessed by multiple threads concurrently.

The ConcurrentDictionary<TKey, TValue> is a Concurrent Collection that stores the element in


the form of Key-Value Pairs. The working of the ConcurrentDictionary<TKey, TValue> is very much similar to
the working of the Generic Dictionary<TKey, TValue> collection class. The only difference is that Generic
Dictionary is not thread-safe whereas the ConcurrentDictionary is thread-safe.

Following are some important points that you need to keep in mind while working with ConcurrentDictionary
Class in C#.

 In ConcurrentDictionary<TKey, TValue> Collection, the key cannot be null


 Every key in the ConcurrentDictionary<TKey, TValue> Collection must be unique. Duplicate keys are
not allowed. But if multiple threads try to add duplicate keys, then it will not allow and it will not throw
any exception.
 In ConcurrentDictionary<TKey, TValue> Collection, you can only store the same types of elements as it
is generic and while creating the ConcurrentDictionary instance we need to specify the types for both
key and values.

Prof. Honrao Bhagyashri Prakash (36 )


Shriram Institute of Information Technology, Paniv

 The capacity of a ConcurrentDictionary collection is the number of elements that the


ConcurrentDictionary can hold.
 The ConcurrentDictionary<TKey, TValue> collection is dynamic in nature means the size of the
collection is automatically increased as we added items to the collection.
 Syntax-
ConcurrentDictionary<KeyDataType, ValuDataType> dictionary_name = new
ConcurrentDictionary<KeyDataType, ValuDataType>();

The following are the methods of ConcurrentDictionary class –

1) TryAdd(TKey key, TValue value): The TryAdd(TKey key, TValue value) method is used to add
an element with the specified key and value into the ConcurrentDictionary collection.
2) ContainsKey(TKey key): The ContainsKey(TKey key) method of the ConcurrentDictionary class
is used to check if the given key is present in the ConcurrentDictionary or not.
3) TryRemove(TKey key, out TValue value): This method attempts to remove and return the value
that has the specified key from the ConcurrentDictionary.
4) Clear(): This method is used to remove all elements i.e. all the keys and values from the
ConcurrentDictionary object.
5) TryUpdate(TKey key, TValue newValue, TValue comparisonValue): This method is used to
update the value associated with the key to newValue if the existing value with the key is equal to
the comparison value.
6) GetOrAdd(TKey key, Func<TKey, TValue> valueFactory): This method is used to add a
key/value pair to the ConcurrentDictionary by using the specified function if the key does not
already exist. Returns the new value, or the existing value if the key exists. The following are the
parameters used in this method.
key: The key of the element to add.
valueFactory: The function used to generate a value for the key.
7) GetOrAdd(TKey key, TValue value): This method is used to add a key/value pair to the
ConcurrentDictionary if the key does not already exist. Returns the new value, or the existing value
if the key exists. The following are the parameters used in this method.
key: The key of the element to add.
value: The value to be added, if the key does not already exist.

Program: -
using System;
using System.Threading;

Prof. Honrao Bhagyashri Prakash (37 )


Shriram Institute of Information Technology, Paniv

using System.Collections.Concurrent;
using System.Collections.Generic;
namespace ConcurrentCollections
{
class Program
{
static ConcurrentDictionary<int, string> dictionary = new ConcurrentDictionary<int, string>();
static void Main(string[] args)
{
Thread t1 = new Thread(Method1);
Thread t2 = new Thread(Method2);
t1.Start();
t2.Start();
t1.Join();
t2.Join();
foreach (KeyValuePair<int, string> item in dictionary)
{
Console.WriteLine($"Key:{item .Key}, Value:{item .Value}");
}
Console.ReadKey();
}
public static void Method1()
{
for (int i = 0; i < 10; i++)
{
dictionary.TryAdd(i, "Added By Method1 " + i);
Thread.Sleep(100);
}
}
public static void Method2()
{
for (int i = 0; i < 10; i++)
{
dictionary.TryAdd(i, "Added By Method2 " + i);
Thread.Sleep(100);

Prof. Honrao Bhagyashri Prakash (38 )


Shriram Institute of Information Technology, Paniv

}
}
}
}
Output : -

2) ConcurrentQueue<T>: Thread-safe version of the generic queue (FIFO Data Structure)


 The ConcurrentQueue<T> is a Thread-Safe Collection Class in C#. It was introduced as part of C# 4.0
and it belongs to System.Collections.Concurrent namespace.
 It provides a Thread-Safe First-In-First-Out (FIFO) data structure.
 That means we need to go for ConcurrentQueue<T> Collection when we need First in First Out (FIFO)
access to items of a collection in a multi-threaded environment with thread safety.
 The working of the ConcurrentQueue<T> is very much similar to the working of the Generic Queue<T>
collection class.
 The only difference between them is that Generic Queue<T> is not thread-safe whereas the
ConcurrentQueue<T> is thread-safe.
 Syntax –
ConcurrentQueue<int> queue= new ConcurrentQueue<int>();

The following are the methods and properties of ConcurrentQueue<T> class –

a) Enqueue() - We can use the Enqueue method to add elements to our queue in a safe and orderly
manner:
b) TryDequeue() - This method tries to remove and return the object at the beginning of the concurrent
queue. This method returns true if an element was removed and returned from the beginning of the
ConcurrentQueue successfully; otherwise, false.
c) TryPeek() - Return first item from ConcurrentQueue.
d) Clear() - The Clear method efficiently removes all items from the queue, leaving it empty and ready for
new data.
e) Count - The Count property allows us to quickly check how many items are currently in the queue.

Program: -

using System;

Prof. Honrao Bhagyashri Prakash (39 )


Shriram Institute of Information Technology, Paniv

using System.Collections.Concurrent;
namespace ConcurrentQueueDemo
{
class Program
{
static void Main(string[] args)
{
ConcurrentQueue<int> concurrentQueue = new ConcurrentQueue<int>();
concurrentQueue.Enqueue(10);
concurrentQueue.Enqueue(20);
concurrentQueue.Enqueue(30);
concurrentQueue.Enqueue(40);
Console.WriteLine($"All Concurrent Queue Elements Count: {concurrentQueue.Count}");
foreach (var item in concurrentQueue)
{
Console.WriteLine(item);
}
bool IsRemoved = concurrentQueue.TryDequeue(out int Result1);
Console.WriteLine($"\nTryDequeue Return : {IsRemoved}");
Console.WriteLine($"TryDequeue Result Value : {Result1}");
Console.WriteLine($"All Concurrent Queue Elements After TryDequeue: Count
{concurrentQueue.Count}");
foreach (var element in concurrentQueue)
{
Console.WriteLine($"{element} ");
}
Console.ReadLine();
}
}
}

Output : -

3) ConcurrentStack<T> class:

Prof. Honrao Bhagyashri Prakash (40 )


Shriram Institute of Information Technology, Paniv

 The ConcurrentStack<T> is a Thread-Safe Collection Class in C#.


 It was introduced as part of .NET Framework 4.0 and it belongs to System.Collections.Concurrent
namespace.
 It provides a thread-safe Last-In-First-Out (LIFO) data structure. That means we need to go for
ConcurrentStack<T> Collection when we need Last in First Out (LIFO) access to the collection
elements in a multi-threaded environment with thread safety.
 The working of the ConcurrentStack<T> is very much similar to the working of the Generic Stack<T>
Collection Class in C#.
 The only difference between them is that the Generic Stack<T> Collection is not thread-safe whereas
the ConcurrentStack<T> is thread-safe.
 So, we can use the Generic Stack class instead of ConcurrentStack with multiple threads, but in that
case, as a developer, we need to use locks explicitly to provide thread safety which is always time-
consuming and error-prone
Syntax:
ConcurrentStack<type> ConcurrentStack _Name = new ConcurrentStack<type>();

The following are the methods and properties of ConcurrentStack <T> class –

a) Push: Add item at top of ConcurrentStack.


b) PushRange: Tries to add multiple items at top of ConcurrentStack.
c) TryPeek: Tries to return last item from ConcurrentStack.
d) TryPop: Tries to pop and return last item from ConcurrentStack.
e) TryPop(out T result): This method attempts to pop and return the object at the top of the
ConcurrentStack.
f) tryPopRange(T[] items): This method attempts to pop and return multiple objects from the top of the
ConcurrentStack atomically.
g) TryPeek(out T result): This method attempts to return an object from the top of the ConcurrentStack
without removing it.

Program
using System;
using System.Collections.Concurrent;
namespace ConcurrentStackDemo
{
class Program

Prof. Honrao Bhagyashri Prakash (41 )


Shriram Institute of Information Technology, Paniv

{
static void Main(string[] args)
{
ConcurrentStack<string> concurrentStack = new ConcurrentStack<string>();
concurrentStack.Push("India");
concurrentStack.Push("USA");
concurrentStack.Push("UK");
concurrentStack.Push("Canada");
concurrentStack.Push("Japan");
Console.WriteLine($"ConcurrentStack Elements Count: {concurrentStack.Count}");
foreach (var item in concurrentStack)
{
Console.WriteLine(item);
}
bool IsRemoved = concurrentStack.TryPop(out string Result1);
Console.WriteLine($"\nTryPop Return : {IsRemoved}");
Console.WriteLine($"TryPop Result Value : {Result1}");
//Printing Elements After Removing the Top Element
Console.WriteLine($"\nConcurrentStack Elements After TryPop: Count
{concurrentStack.Count}");
foreach (var element in concurrentStack)
{
Console.WriteLine($"{element} ");
}
Console.ReadLine();

}
}
}

Output-

ConcurrentStack Elements Count: 5


Japan
Canada
UK
USA

Prof. Honrao Bhagyashri Prakash (42 )


Shriram Institute of Information Technology, Paniv

India
TryPop Return : True
TryPop Result Value : Japan
ConcurrentStack Elements After TryPop: Count 4
Canada
UK
USA
India
TryPeek

4) ConcurrentBag<T>: Thread-safe implementation of an unordered collection.

 The ConcurrentBag<T> is a Thread-Safe Collection Class in C#. It was introduced as part of .NET
Framework 4.0 and it belongs to System.Collections.Concurrent namespace.
 It allows generic data to be stored in the unordered form. It allows you to store duplicate objects.
 The working of the ConcurrentBag<T> is very much similar to the working of the Generic List<T>
Collection Class in C#.
 The only difference between them is that the Generic List<T> Collection is not thread-safe whereas the
ConcurrentBag<T> is thread-safe.

Syntax:

ConcurrentBag<string> concurrentBag = new ConcurrentBag<string>();

OR

ConcurrentBag<string> concurrentBag = new ConcurrentBag<string>


{
"India", "USA", "UK", "Canada"
};

The following are the methods and properties of ConcurrentBag <T> class –

a) Add:: Add item into ConcurrentBag collection.


b) TryTake: Tries to remove and return item from ConcurrentBag.
c) TryPeek: Tries to return item from ConcurrentBag.

Prof. Honrao Bhagyashri Prakash (43 )


Shriram Institute of Information Technology, Paniv

Program

using System;

using System.Collections.Concurrent;

namespace ConcurrentBagDemo

class Program

static void Main(string[] args)

ConcurrentBag<string> concurrentBag = new ConcurrentBag<string>();

concurrentBag.Add("India");

concurrentBag.Add("USA");

concurrentBag.Add("UK");

Console.WriteLine($"ConcurrentBag All Elements: Count {concurrentBag.Count}");

foreach (var element in concurrentBag)

Console.WriteLine($"{element} ");

bool IsRemoved = concurrentBag.TryTake(out string Result1);

Console.WriteLine($"\nTryTake Return : {IsRemoved}");

Console.WriteLine($"TryTake Result Value : {Result1}");

Console.WriteLine($"\nConcurrentBag Elements After TryTake: Count


{concurrentBag.Count}");

foreach (var element in concurrentBag)

Console.WriteLine($"{element} ");

Console.ReadLine();

Prof. Honrao Bhagyashri Prakash (44 )


Shriram Institute of Information Technology, Paniv

Output –

ConcurrentBag All Elements: Count 3


UK
USA
India
TryTake Return : True
TryTake Result Value : UK
ConcurrentBag Elements After TryTake: Count 2
USA
India

5) BlockingCollection<T>: Provides a Classical Producer-Consumer pattern.


 The BlockingCollection is a Concurrent Collection Class in C# which provides thread safety. That
means multiple threads can add as well as remove objects from the BlockingCollection concurrently.
 The BlockingCollection implements the Producer-Consumer Pattern in C#.
 In Producer-Consumer Pattern, we have two threads one is called the Producer thread and another one is
called the Consumer thread.
 And most important point is that both the threads will share a common collection class to exchange the
data between them.
 And that scenario, we can use BlockingCollection as the collection class which will be shared by both
Producer and Consumer threads.
Syntax:

BlockingCollection<type> BlockingCollection_Name = new BlockingCollection<type>();

The following are the methods and properties of BlockingCollection <T> class –

a) Add(T item): This method is used to add the item to the BlockingCollection. Add method takes a single
parameter i.e. the item to be added to the collection.
b) TryAdd(T item): This method tries to add the specified item to the BlockingCollection. The parameter
item to be added to the collection. It returns true if the item could be added; otherwise, false.

Prof. Honrao Bhagyashri Prakash (45 )


Shriram Institute of Information Technology, Paniv

c) Take(): This method is used to remove an item from the BlockingCollection. It returns the item
removed from the collection. The Take method is blocked when the collection is empty. It‟ll unblock
automatically when an item is added by another thread.
d) TryTake(out T item): This method tries to remove an item from the BlockingCollection. It will store
the removed item in the output item.
Program

using System;
using System.Collections.Concurrent;
namespace ConcurrentBagDemo
{
class Program
{
static void Main()
{
BlockingCollection<int> blockingCollection = new BlockingCollection<int>(4);
blockingCollection.Add(10);
blockingCollection.Add(20);
blockingCollection.TryAdd(40);
blockingCollection.TryAdd(50);
if (blockingCollection.TryAdd(30,TimeSpan.FromSeconds(1)))
{
Console.WriteLine("Item 30 Added");
}
else
{
Console.WriteLine("Item 30 Not added");
}
Console.WriteLine("\nAll BlockingCollection Elements");
foreach (var item in blockingCollection)
{
Console.WriteLine(item);
}
int Result1 = blockingCollection.Take();

Console.WriteLine($"\nItem Removed By Take Method: {Result1}");

Prof. Honrao Bhagyashri Prakash (46 )


Shriram Institute of Information Technology, Paniv

Console.ReadKey();
}
}
}
Output –
Item 30 Not added
All BlockingCollection Elements
10
20
40
50
Item Removed By Take Method: 10

 Resource Management –
Resource management in C# is important for building efficient and robust applications.
Here are some ways to manage resources in C#:
1) Finalizers
2) Garbage Collection
3) IDisposable
4) The using statement

1) Finalizers : -
Finalizers are methods in object-oriented programming (e.g., C#) that allow you to perform
cleanup operations before an object is reclaimed by the garbage collector.
 They are defined using a special syntax (like ~ClassName() in C#) and are called when the garbage
collector identifies that an object is no longer in use.
 Finalizers are exactly opposite of constructor.
 Finalizers cannot be defined in structs. They are only used with classes.
 Finalizers are used to destruct instances of classes.
 A class can have only one finalizer.
 Finalizers cannot be inherited or overloaded.
 Finalizers cannot be called.They are invoked automatically.
 A finalizer does not take modifiers or have parameters.

Prof. Honrao Bhagyashri Prakash (47 )


Shriram Institute of Information Technology, Paniv

Syntax;
~classname( )
Example:
using System;
class first
{
~first()
{
Console.WriteLine("first class destory");
}
}
class second:first
{
~second()
{
Console.WriteLine("second class destory");
}
}
class third:second
{
~third()
{
Console.WriteLine("third class destory");
}
public static void Main(String [] args)
{
third t=new third();
}

Output:
third class destory
second class destory
first class destroy

Prof. Honrao Bhagyashri Prakash (48 )


Shriram Institute of Information Technology, Paniv

2) Garbage Collection
 Garbage collection is a memory management technique used in the .NET Framework and
many other programming languages.
 In C#, the garbage collector is responsible for managing memory and automatically freeing up
memory that is no longer being used by the application.
 The garbage collector works by periodically scanning the application‟s memory to determine which
objects are still being used and which are no longer needed.
 Objects that are no longer being used are marked for garbage collection, and their memory is freed
up automatically by the garbage collector.
 When a class object is created at runtime, a certain memory space is allocated to it in the heap
memory. However, after all the actions related to the object are completed in the program, the
memory space allocated to it is a waste as it cannot be used. In this case, garbage collection is very
useful as it automatically releases the memory space after it is no longer required.
 GC.Collect()
This method requires a single parameter i.e. number of the oldest generation for which garbage
collection occurs.
Example:
using System;
namespace ConcurrentCollections
{
public class MyClass
{
~MyClass()
{
Console.WriteLine("Garbage collection called.");
Console.ReadLine();
}
}
public class Program
{
public static void Main(String[] args)
{
MyClass obj = new MyClass();
GC.Collect();

Prof. Honrao Bhagyashri Prakash (49 )


Shriram Institute of Information Technology, Paniv

Console.ReadLine();
}
}
}
Output:
Garbage collection called.

3) IDisposable
 IDisposable is an interface defined in the System namespace.
 IDisposable is an interface that contains a single method, Dispose(), for releasing unmanaged
resources, like files, streams, database connections and so on.
 This method is implemented explicitly in the code when we need to clean up a disposable object and
to release unmanaged resources that this disposable object holds.
 The class implementing IDisposable interface must implement the dispose method.
 The disposal method should be called only once. To ensure that we use a boolean variable.
 If a base class is implementing IDisposable interface the derived classes should not implement the
interface again.
 The Derived class can override the dispose(bool disposing) method and release its resources.

4) The using statement


 The C# using statement defines a boundary for the object outside of which, the object is
automatically destroyed.
 The "using" statement allows you to specify multiple resources in a single statement.
 The object could also be created outside the "using" statement.
 The framework invokes the Dispose method of objects specified within the "using" statement
when the block is exited.
 When you use the using statement, C# will automatically call the Dispose method on the object
when it's no longer needed.
 This means you don't have to manually call the Dispose method or worry about forgetting to do
so. The using statement takes care of this for you!
Example:
using System;
namespace ConcurrentCollections

Prof. Honrao Bhagyashri Prakash (50 )


Shriram Institute of Information Technology, Paniv

{
public class MyClass:IDisposable
{
public void Dispose()
{
Console.WriteLine("I am Disposing...");
}
}
public class Program
{
public static void Main(String[] args)
{
using (var disposableItem = new MyClass())
{
Console.WriteLine("Inside of the using statement...");
}
Console.ReadLine();
}
}
}
Output:

Inside of the using statement...


I am Disposing...

 Serialization:
“The process of converting an object into a stream of bytes is called Serialization ”
Apply the [Serializable( )] Attribute to a type to indicate that instances of this type can be Serialized.

 Deserialization:
“The process of converting object from that stream of bytes is called Serialization ”
If you do not want a field within your class to be serializable,apply the [NonSerialized( )] Attribute.

Prof. Honrao Bhagyashri Prakash (51 )


Shriram Institute of Information Technology, Paniv

 JSON Serialization
 JSON (JavaScript Object Notation) serialization involves converting objects into a JSON format that can
be easily transmitted or stored.
 This is widely used in web applications and APIs.
 Libraries like Newtonsoft.Json in .NET or built-in json modules in Python facilitate JSON serialization
and deserialization, allowing objects to be converted to JSON strings and back.
 We need to install using Newtonsoft.Json package in visual command prompt use following command

dotnet add package Newtonsoft.Json


(also use dotnet fiddle website)
Program: -

using Newtonsoft.Json;
using System;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
var person = new Person { Name = "Alice", Age = 30 };
// Serialize to JSON
string json = JsonConvert.SerializeObject(person);
Console.WriteLine(json); // {"Name":"Alice","Age":30}
// Deserialize from JSON
var dp = JsonConvert.DeserializeObject<Person>(json);
Console.WriteLine(dp.Name); // Alice
}

Prof. Honrao Bhagyashri Prakash (52 )


Shriram Institute of Information Technology, Paniv

}
Output:
{
"Name":"Alice",

"Age":30
}
Alice

 Binary Serialization
 Converting an Object to a Binary format which is not in a human readable format is called Binary
Serialization.
 To achieve binary serialization in C# we have to make use of library
System.Runtime.Serialization.Formatters.Binary Assembly
 Create an object of BinaryFormatter class and make use of serialize method inside the class.
 Binary serialization involves converting an object into a binary format.
 Binary formats can be less human-readable compared to text formats like JSON or XML. In .NET, for
instance, the BinaryFormatter class can be used for binary serialization.
Program: -

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

public class Person


{
public string Name;
public int Age;
}
public class Program
{
public static void Main()
{

Prof. Honrao Bhagyashri Prakash (53 )


Shriram Institute of Information Technology, Paniv

var person = new Person { Name = "Bob", Age = 25 };


// Serialize the object to a MemoryStream
IFormatter formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, person);
Console.WriteLine("Object serialized to memory.");
// Reset the stream position to the beginning for deserialization
stream.Seek(0, SeekOrigin.Begin);
// Deserialize the object from the MemoryStream
var deserializedPerson = (Person)formatter.Deserialize(stream);
Console.WriteLine("Deserialized Person: Name =
{deserializedPerson.Name}, Age = {deserializedPerson.Age}");
}
}
}

Output:

Object serialized to memory.


Deserialized Person: Name = Bob, Age = 25

 XML Serialization

 XML (eXtensible Markup Language) serialization is the process of converting objects to


an XML format.
 XML is human-readable and widely used for data interchange between systems. In .NET,
the XmlSerializer class can be employed to serialize and deserialize objects to and from
XML
 It provides a good balance of readability and compatibility, making it suitable for
configuration files and web services.
 Use using System.Xml.Serialization namespace;

Prof. Honrao Bhagyashri Prakash (54 )


Shriram Institute of Information Technology, Paniv

Program : -
using System;
using System.IO;
using System.Xml.Serialization;
public class Person
{

public string Name { get; set; }


public int Age { get; set; }
}
public class Program
{
public static void Main()
{
var person = new Person { Name = "Charlie", Age = 35 };
// Serialize to XML
var xmlSerializer = new XmlSerializer(typeof(Person));
using (var writer = new StringWriter())
{
xmlSerializer.Serialize(writer, person);
string xml = writer.ToString();
Console.WriteLine(xml); // XML output
}
// Deserialize from XML
using (var reader = new
StringReader("<Person><Name>Charlie</Name><Age>35</Age></
Person>"))
{
var deserializedPerson = (Person)xmlSerializer.Deserialize(reader);
Console.WriteLine(deserializedPerson.Name); // Charlie

Prof. Honrao Bhagyashri Prakash (55 )


Shriram Institute of Information Technology, Paniv

<?xml version="1.0" encoding="utf-16"?>


<Person xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name>Charlie</Name>
<Age>35</Age>
</Person>
Output:-

Charlie

Prof. Honrao Bhagyashri Prakash (56 )

You might also like