SlideShare a Scribd company logo
Advanced
Programming Topics
CSI 571
Objectives:
 Multithreaded Applications
 Thread Life Cycle
 Thread Scheduling & Synchronization
 Creating and Using Delegates
 Events as special Delegates
 The Standard Event Handler
 Inheritance
Multithreaded Programming
 The benefits of multithreaded programming
can be broken down into four major
categories:
 Responsiveness
 Resource sharing
 Economy
 Utilization
Multithreaded Programming: C# Example
using System;
using System.Threading;
public class ThreadedCounters {
public static void Main(){
Thread thread1 = new Thread(new ThreadStart(Counter1));
thread1.Start();
Thread thread2 = new Thread(new ThreadStart(Counter2));
thread2.Start();
}
public static void Counter1() {
for (int i = 0; i<10; i++) {
Console.WriteLine("Counter 1: "+i);
Thread.Sleep(35);
}
}
public static void Counter2() {
for (int i = 0; i<10; i++) {
Console.WriteLine("Counter 2: "+i);
Thread.Sleep(20);
}
}
}
Thread Life Cycle
 A common problem that needs to be handled
when writing multithreaded program is thread
synchronization
 This is necessary where more than one thread
needs to modify a certain object at a time
 Let us consider the following unsafe banking
example demonstrating the need for
synchronization
Thread Scheduling & Synchronization:
Multithreaded Programming: C# Example
using System;
using System.Threading;
public class BankAccount {
int balance = 0;
public BankAccount(int initial) {
balance = initial;
}
public void Deposit(int amount) {
balance+=amount;
}
public void Withdraw(int amount) {
balance-=amount;
}
public int GetBalance() {
return balance;
}
}
public class UnsafeBanking {
static Random randomizer = new Random();
static BankAccount account = new BankAccount(100);
public static void Main() {
Thread[] banker = new Thread[10];
for (int i=0; i<10; i++) {
banker[i] = new Thread(new
ThreadStart(DepositWithdraw));
banker[i].Start();
}
}
public static void DepositWithdraw() {
int amount = randomizer.Next(100);
account.Deposit(amount);
Thread.Sleep(100);
account.Withdraw(amount);
Console.WriteLine(account.GetBalance());
}
}
Add a Slide TitleM - 1
Thread Scheduling & Synchronization:
 From the previous code, since the amount being
deposited is the same as the amount withdrawn,
one would expect the balance to remain unchanged
 But, this is not what happens as the following
output shows:
Solving the
Synchronization
in C#:
 C# uses the Monitor Class, which provides two
static methods, Enter and Exit
 The Enter method is used to obtain a lock on an
object that the monitor guards and is called
before accessing the object
 If the lock is currently owned by another thread,
the thread that calls Enter blocks
 That is, the thread is taken off the processor and
placed in a very efficient wait state until the lock
becomes free
 Exit frees the lock after the access is complete
so that other threads can access the resource
Solving the Synchronization in C#:
public static void DepositWithdraw() {
int amount = randomizer.Next(100);
Monitor.Enter(account);
try {
account.Deposit(amount);
Thread.Sleep(100);
account.Withdraw(amount);
Console.WriteLine(account.GetBalance());
}
finally {
Monitor.Exit(account); } }
public static void DepositWithdraw() {
int amount = randomizer.Next(100);
lock(account) {
account.Deposit(amount);
Thread.Sleep(100);
account.Withdraw(amount);
Console.WriteLine(account.GetBalance());
}
}
Delegates
 A Delegate is a class whose declaration syntax
is different from that of a normal class
 It is used to hold references to methods, so
that when it is invoked, it automatically invokes
all methods associated with it
 Thus, a delegate gives an indirect access to a
method or methods, hence the name delegate
Delegates
using System;
public class DelegateExample {
public delegate void PrintingDelegate(String s);
public static void Writer1(String s) {
Console.WriteLine("From Writer1: "+s); }
public static void Writer2(String s) {
Console.WriteLine("From Writer2: "+s); }
public static void Main() {
PrintingDelegate d = new PrintingDelegate(Writer1);
d("Hello There");
//can point to more than one method
d += new PrintingDelegate(Writer2);
Console.WriteLine();
d("Hello There");
//can also point to instance method
Console.WriteLine();
MessageWriter mw = new MessageWriter();
d+= new PrintingDelegate(mw.WriteMessage);
d("Hello There");
//You can also remove a method
Console.WriteLine();
d-= new PrintingDelegate(Writer1);
d("Hello There"); } }
public class MessageWriter {
public void WriteMessage(String s) {
Console.WriteLine("From MessageWriter: "+s); }}
Delegate Declaration
 Notice that although delegate is a class, its
declaration syntax is very similar to that of a
method
 It is designed this way because a delegate can only
hold references to specific types of methods –
those methods whose signature matched that of
the delegate.
 Thus, in our example, the PrintingDelegate can only
hold references to methods of the form:
[static] void MethodName(String s)
 As the above example shows, such methods can be
static or instance
Instantiating a
Delegate
 Before you create an instance of a delegate, you
must have a method that you wish to associate
that instance with. As we can see from the
example, the syntax is:
 DelegateType delegateVar = new
DelegateType(methodName);
 Notice that the method name must NOT be
followed with parameters
 Actually a method name without parameter means
a reference to the method. So the above
statement assigns the method reference to the
delegateVar delegate instance
Inheritance
 Generally speaking, objects are defined in terms
of classes. You know a lot about an object by
knowing its class
 Inheritance offers the following benefits:
 Subclasses provide specialized behaviors from the
basis of common elements provided by the superclass
 Through the use of inheritance, programmers can reuse
the code in the superclass many times
 Programmers can implement superclasses called
abstract classes that define common behaviors
• The abstract superclass defines and may partially
implement the behavior, but much of the class is
undefined and unimplemented. Other programmers fill in
the details with specialized subclasses.
Inheritance
 The following is specific to C#
 Again there is no “extend” keyword. Instead, the same
colon used for “implements” is used
 If a class extends a class and implements one or more
interfaces, there should be only one colon
 The super class and the interfaces are then listed
separated by commas
 Notice that if there is a super class being extended,
then it must appear first in the list
Inheritance
 The keyword, base, is used instead of the Java’s super, to
refer to a superclass member.
 Also it is used to call the constructor of the base class from
within a subclass. However, like this keyword, such a call
should be in the heading of the calling constructor.
 Example:
class B:A {
public B : base(. . .) {
. . .
} }
Inheritance
 Overriding & Hiding
 In C#, overriding is not allowed by default.
 The base class must indicate that it is willing to allow its
method to be overridden by declaring the method as
virtual, abstract or override.
 The subclass must also indicate that it is overriding the
method by using the override keyword.
 The effect of overriding is the same as in Java –
Polymorphism. At run-time, a method call will be bound to
the method of the actual object.
 A subclass may also decide to hide an inherited method
instead of overriding it by using the new keyword as the
following example shows.
Overriding,
Hiding Example
in C#
using System;
class A {
public virtual void method() {
Console.WriteLine(" In A");
}
}
class B : A {
public override void method() {
Console.WriteLine("In B");
}
}
class C : B {
public new void method() {
Console.WriteLine("In C");
}
}
class Test {
public static void Main() {
C c = new C();
c.method(); // calls C's method
B b = c;
b.method(); //calls B's method
A a = c;
a.method(); //calls B's method
}
}
Interfaces
 In general, an interface is a device or a system that
unrelated entities use to interact
 Interfaces are used to minimize the effect of lack of
multiple inheritance
 Interfaces contain only method specification without
implementation
 Unlike Java, interfaces cannot have even constant
fields
 A class can implement multiple interfaces. However,
there is no “implements” keyword. Instead, a colon is
used for implements
Interfaces
 You use an interface to define a protocol of behavior
that can be implemented by any class anywhere in the
class hierarchy. Interfaces are useful for the
following:
 Capturing similarities among unrelated classes without
artificially forcing a class relationship
 Declaring methods that one or more classes are expected to
implement
 Revealing an object's programming interface without
revealing its class
 Modeling multiple inheritance, a feature that some object-
oriented languages support that allows a class to have more
than one superclass
Thank you
Asma Ali

More Related Content

What's hot (20)

PPT
Simple Java Programs
AravindSankaran
 
PPTX
Java - Generic programming
Riccardo Cardin
 
PPTX
C Programming Unit-1
Vikram Nandini
 
PPTX
C Programming Unit-2
Vikram Nandini
 
DOC
CS2309 JAVA LAB MANUAL
Lavanya Arunachalam A
 
PPTX
Overview of c++ language
samt7
 
DOCX
Java codes
Hussain Sherwani
 
PDF
Le langage rust
Geeks Anonymes
 
PDF
66781291 java-lab-manual
Laura Popovici
 
PDF
Generic programming
Platonov Sergey
 
PPT
01 c++ Intro.ppt
Tareq Hasan
 
DOC
Java programming lab assignments
rajni kaushal
 
ODP
Ppt of c++ vs c#
shubhra chauhan
 
PDF
Intake 38 5 1
Mahmoud Ouf
 
PPT
Qno 2 (a)
Praveen M Jigajinni
 
PDF
Deep C
Olve Maudal
 
PDF
C++ Training
SubhendraBasu5
 
PPSX
C++ Programming Language
Mohamed Loey
 
PPTX
Templates presentation
malaybpramanik
 
Simple Java Programs
AravindSankaran
 
Java - Generic programming
Riccardo Cardin
 
C Programming Unit-1
Vikram Nandini
 
C Programming Unit-2
Vikram Nandini
 
CS2309 JAVA LAB MANUAL
Lavanya Arunachalam A
 
Overview of c++ language
samt7
 
Java codes
Hussain Sherwani
 
Le langage rust
Geeks Anonymes
 
66781291 java-lab-manual
Laura Popovici
 
Generic programming
Platonov Sergey
 
01 c++ Intro.ppt
Tareq Hasan
 
Java programming lab assignments
rajni kaushal
 
Ppt of c++ vs c#
shubhra chauhan
 
Intake 38 5 1
Mahmoud Ouf
 
Deep C
Olve Maudal
 
C++ Training
SubhendraBasu5
 
C++ Programming Language
Mohamed Loey
 
Templates presentation
malaybpramanik
 

Similar to Advanced programming topics asma (20)

PPT
Synapseindia dot net development
Synapseindiappsdevelopment
 
DOCX
C# Unit 2 notes
Sudarshan Dhondaley
 
PPTX
CSharp Presentation
Vishwa Mohan
 
PPTX
Inheritance
Mavoori Soshmitha
 
PPTX
FINAL_DAY10_INTERFACES_roles and benefits.pptx
VGaneshKarthikeyan
 
PPTX
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
yazad dumasia
 
PDF
Object-oriented programming (OOP) with Complete understanding modules
Durgesh Singh
 
PPTX
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
PPT
Csharp4 inheritance
Abed Bukhari
 
PPT
Csharp_mahesh
Ananthu Mahesh
 
PPT
Object Oriented Programming with Java
backdoor
 
PDF
C Sharp: Basic to Intermediate Part 01
Zafor Iqbal
 
DOCX
Srgoc dotnet
Gaurav Singh
 
PDF
LEARN C#
adroitinfogen
 
DOCX
I assignmnt(oops)
Jay Patel
 
DOCX
Sdtl assignment 03
Shrikant Kokate
 
PDF
C# interview-questions
nicolbiden
 
PPT
polymorphism.ppt
Shubham79233
 
Synapseindia dot net development
Synapseindiappsdevelopment
 
C# Unit 2 notes
Sudarshan Dhondaley
 
CSharp Presentation
Vishwa Mohan
 
Inheritance
Mavoori Soshmitha
 
FINAL_DAY10_INTERFACES_roles and benefits.pptx
VGaneshKarthikeyan
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
yazad dumasia
 
Object-oriented programming (OOP) with Complete understanding modules
Durgesh Singh
 
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
Csharp4 inheritance
Abed Bukhari
 
Csharp_mahesh
Ananthu Mahesh
 
Object Oriented Programming with Java
backdoor
 
C Sharp: Basic to Intermediate Part 01
Zafor Iqbal
 
Srgoc dotnet
Gaurav Singh
 
LEARN C#
adroitinfogen
 
I assignmnt(oops)
Jay Patel
 
Sdtl assignment 03
Shrikant Kokate
 
C# interview-questions
nicolbiden
 
polymorphism.ppt
Shubham79233
 
Ad

Recently uploaded (20)

PPTX
FACTORS PREDISPOSING TO MICROBIAL PATHOGENICITY.pptx
Remya M S
 
PDF
Driving down costs for fermentation: Recommendations from techno-economic data
The Good Food Institute
 
PDF
Thermal stratification in lakes-J. Bovas Joel.pdf
J. Bovas Joel BFSc
 
PPTX
(Normal Mechanism)physiology of labour.pptx
DavidSalman2
 
PPTX
Operating_a_Microscope_Presentation.pptx
MerylVelardeCapapas
 
PPTX
PROTECTED CULTIVATION ASSIGNMENT 2..pptx
RbDharani
 
PPTX
Cyclotron_Presentation_theory, designMSc.pptx
MohamedMaideen12
 
PPT
Gene expression and regulation University of Manchester
hanhocpt13
 
PPTX
PROTOCOL PREsentation.pptx 12345567890q0
jeevika54
 
PPT
rate of reaction and the factors affecting it.ppt
MOLATELOMATLEKE
 
PDF
Integrating Conversational Agents and Knowledge Graphs within the Scholarly D...
Angelo Salatino
 
PDF
seedproductiontechniques-210522130809.pdf
sr5566mukku
 
PPTX
Philippine_Literature_Precolonial_Period_Designed.pptx
josedalagdag5
 
PDF
Therapeutic, Functional and Neutralizing Antibodies Recognize Discontinuous, ...
stavejw
 
PDF
The Diversity of Exoplanetary Environments and the Search for Signs of Life B...
Sérgio Sacani
 
PDF
POLISH JOURNAL OF SCIENCE №87 (2025)
POLISH JOURNAL OF SCIENCE
 
PDF
Voyage to the Cosmos of Consciousness.pdf
Saikat Basu
 
PPTX
GENERAL BIOLOGY 1QUARTER 1 MODULE 1 CELL THEORY PPT
MOJANAABIGAILLLAGUNO
 
PPTX
animal form and function zoology miller harley
sarmadbilal3
 
PDF
Electromagnetism 3.pdf - AN OVERVIEW ON ELECTROMAGNETISM
kaustavsahoo94
 
FACTORS PREDISPOSING TO MICROBIAL PATHOGENICITY.pptx
Remya M S
 
Driving down costs for fermentation: Recommendations from techno-economic data
The Good Food Institute
 
Thermal stratification in lakes-J. Bovas Joel.pdf
J. Bovas Joel BFSc
 
(Normal Mechanism)physiology of labour.pptx
DavidSalman2
 
Operating_a_Microscope_Presentation.pptx
MerylVelardeCapapas
 
PROTECTED CULTIVATION ASSIGNMENT 2..pptx
RbDharani
 
Cyclotron_Presentation_theory, designMSc.pptx
MohamedMaideen12
 
Gene expression and regulation University of Manchester
hanhocpt13
 
PROTOCOL PREsentation.pptx 12345567890q0
jeevika54
 
rate of reaction and the factors affecting it.ppt
MOLATELOMATLEKE
 
Integrating Conversational Agents and Knowledge Graphs within the Scholarly D...
Angelo Salatino
 
seedproductiontechniques-210522130809.pdf
sr5566mukku
 
Philippine_Literature_Precolonial_Period_Designed.pptx
josedalagdag5
 
Therapeutic, Functional and Neutralizing Antibodies Recognize Discontinuous, ...
stavejw
 
The Diversity of Exoplanetary Environments and the Search for Signs of Life B...
Sérgio Sacani
 
POLISH JOURNAL OF SCIENCE №87 (2025)
POLISH JOURNAL OF SCIENCE
 
Voyage to the Cosmos of Consciousness.pdf
Saikat Basu
 
GENERAL BIOLOGY 1QUARTER 1 MODULE 1 CELL THEORY PPT
MOJANAABIGAILLLAGUNO
 
animal form and function zoology miller harley
sarmadbilal3
 
Electromagnetism 3.pdf - AN OVERVIEW ON ELECTROMAGNETISM
kaustavsahoo94
 
Ad

Advanced programming topics asma

  • 2. Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates  Events as special Delegates  The Standard Event Handler  Inheritance
  • 3. Multithreaded Programming  The benefits of multithreaded programming can be broken down into four major categories:  Responsiveness  Resource sharing  Economy  Utilization
  • 4. Multithreaded Programming: C# Example using System; using System.Threading; public class ThreadedCounters { public static void Main(){ Thread thread1 = new Thread(new ThreadStart(Counter1)); thread1.Start(); Thread thread2 = new Thread(new ThreadStart(Counter2)); thread2.Start(); } public static void Counter1() { for (int i = 0; i<10; i++) { Console.WriteLine("Counter 1: "+i); Thread.Sleep(35); } } public static void Counter2() { for (int i = 0; i<10; i++) { Console.WriteLine("Counter 2: "+i); Thread.Sleep(20); } } }
  • 6.  A common problem that needs to be handled when writing multithreaded program is thread synchronization  This is necessary where more than one thread needs to modify a certain object at a time  Let us consider the following unsafe banking example demonstrating the need for synchronization Thread Scheduling & Synchronization:
  • 7. Multithreaded Programming: C# Example using System; using System.Threading; public class BankAccount { int balance = 0; public BankAccount(int initial) { balance = initial; } public void Deposit(int amount) { balance+=amount; } public void Withdraw(int amount) { balance-=amount; } public int GetBalance() { return balance; } } public class UnsafeBanking { static Random randomizer = new Random(); static BankAccount account = new BankAccount(100); public static void Main() { Thread[] banker = new Thread[10]; for (int i=0; i<10; i++) { banker[i] = new Thread(new ThreadStart(DepositWithdraw)); banker[i].Start(); } } public static void DepositWithdraw() { int amount = randomizer.Next(100); account.Deposit(amount); Thread.Sleep(100); account.Withdraw(amount); Console.WriteLine(account.GetBalance()); } }
  • 8. Add a Slide TitleM - 1
  • 9. Thread Scheduling & Synchronization:  From the previous code, since the amount being deposited is the same as the amount withdrawn, one would expect the balance to remain unchanged  But, this is not what happens as the following output shows:
  • 10. Solving the Synchronization in C#:  C# uses the Monitor Class, which provides two static methods, Enter and Exit  The Enter method is used to obtain a lock on an object that the monitor guards and is called before accessing the object  If the lock is currently owned by another thread, the thread that calls Enter blocks  That is, the thread is taken off the processor and placed in a very efficient wait state until the lock becomes free  Exit frees the lock after the access is complete so that other threads can access the resource
  • 11. Solving the Synchronization in C#: public static void DepositWithdraw() { int amount = randomizer.Next(100); Monitor.Enter(account); try { account.Deposit(amount); Thread.Sleep(100); account.Withdraw(amount); Console.WriteLine(account.GetBalance()); } finally { Monitor.Exit(account); } } public static void DepositWithdraw() { int amount = randomizer.Next(100); lock(account) { account.Deposit(amount); Thread.Sleep(100); account.Withdraw(amount); Console.WriteLine(account.GetBalance()); } }
  • 12. Delegates  A Delegate is a class whose declaration syntax is different from that of a normal class  It is used to hold references to methods, so that when it is invoked, it automatically invokes all methods associated with it  Thus, a delegate gives an indirect access to a method or methods, hence the name delegate
  • 13. Delegates using System; public class DelegateExample { public delegate void PrintingDelegate(String s); public static void Writer1(String s) { Console.WriteLine("From Writer1: "+s); } public static void Writer2(String s) { Console.WriteLine("From Writer2: "+s); } public static void Main() { PrintingDelegate d = new PrintingDelegate(Writer1); d("Hello There"); //can point to more than one method d += new PrintingDelegate(Writer2); Console.WriteLine(); d("Hello There"); //can also point to instance method Console.WriteLine(); MessageWriter mw = new MessageWriter(); d+= new PrintingDelegate(mw.WriteMessage); d("Hello There"); //You can also remove a method Console.WriteLine(); d-= new PrintingDelegate(Writer1); d("Hello There"); } } public class MessageWriter { public void WriteMessage(String s) { Console.WriteLine("From MessageWriter: "+s); }}
  • 14. Delegate Declaration  Notice that although delegate is a class, its declaration syntax is very similar to that of a method  It is designed this way because a delegate can only hold references to specific types of methods – those methods whose signature matched that of the delegate.  Thus, in our example, the PrintingDelegate can only hold references to methods of the form: [static] void MethodName(String s)  As the above example shows, such methods can be static or instance
  • 15. Instantiating a Delegate  Before you create an instance of a delegate, you must have a method that you wish to associate that instance with. As we can see from the example, the syntax is:  DelegateType delegateVar = new DelegateType(methodName);  Notice that the method name must NOT be followed with parameters  Actually a method name without parameter means a reference to the method. So the above statement assigns the method reference to the delegateVar delegate instance
  • 16. Inheritance  Generally speaking, objects are defined in terms of classes. You know a lot about an object by knowing its class  Inheritance offers the following benefits:  Subclasses provide specialized behaviors from the basis of common elements provided by the superclass  Through the use of inheritance, programmers can reuse the code in the superclass many times  Programmers can implement superclasses called abstract classes that define common behaviors • The abstract superclass defines and may partially implement the behavior, but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized subclasses.
  • 17. Inheritance  The following is specific to C#  Again there is no “extend” keyword. Instead, the same colon used for “implements” is used  If a class extends a class and implements one or more interfaces, there should be only one colon  The super class and the interfaces are then listed separated by commas  Notice that if there is a super class being extended, then it must appear first in the list
  • 18. Inheritance  The keyword, base, is used instead of the Java’s super, to refer to a superclass member.  Also it is used to call the constructor of the base class from within a subclass. However, like this keyword, such a call should be in the heading of the calling constructor.  Example: class B:A { public B : base(. . .) { . . . } }
  • 19. Inheritance  Overriding & Hiding  In C#, overriding is not allowed by default.  The base class must indicate that it is willing to allow its method to be overridden by declaring the method as virtual, abstract or override.  The subclass must also indicate that it is overriding the method by using the override keyword.  The effect of overriding is the same as in Java – Polymorphism. At run-time, a method call will be bound to the method of the actual object.  A subclass may also decide to hide an inherited method instead of overriding it by using the new keyword as the following example shows.
  • 20. Overriding, Hiding Example in C# using System; class A { public virtual void method() { Console.WriteLine(" In A"); } } class B : A { public override void method() { Console.WriteLine("In B"); } } class C : B { public new void method() { Console.WriteLine("In C"); } } class Test { public static void Main() { C c = new C(); c.method(); // calls C's method B b = c; b.method(); //calls B's method A a = c; a.method(); //calls B's method } }
  • 21. Interfaces  In general, an interface is a device or a system that unrelated entities use to interact  Interfaces are used to minimize the effect of lack of multiple inheritance  Interfaces contain only method specification without implementation  Unlike Java, interfaces cannot have even constant fields  A class can implement multiple interfaces. However, there is no “implements” keyword. Instead, a colon is used for implements
  • 22. Interfaces  You use an interface to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are useful for the following:  Capturing similarities among unrelated classes without artificially forcing a class relationship  Declaring methods that one or more classes are expected to implement  Revealing an object's programming interface without revealing its class  Modeling multiple inheritance, a feature that some object- oriented languages support that allows a class to have more than one superclass