SlideShare a Scribd company logo
1 of 23
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)

Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language
 
Java codes
Java codesJava codes
Java codes
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
 
Generic programming
Generic programmingGeneric programming
Generic programming
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Intake 38 5 1
Intake 38 5 1Intake 38 5 1
Intake 38 5 1
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Qno 2 (a)
Qno 2 (a)Qno 2 (a)
Qno 2 (a)
 
Deep C
Deep CDeep C
Deep C
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 

Similar to Advanced programming topics asma

Similar to Advanced programming topics asma (20)

Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
Csharp generics
Csharp genericsCsharp generics
Csharp generics
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
Inheritance
InheritanceInheritance
Inheritance
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
 
Object-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modulesObject-oriented programming (OOP) with Complete understanding modules
Object-oriented programming (OOP) with Complete understanding modules
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Csharp4 inheritance
Csharp4 inheritanceCsharp4 inheritance
Csharp4 inheritance
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
C#2
C#2C#2
C#2
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
 
LEARN C#
LEARN C#LEARN C#
LEARN C#
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
 
Sdtl assignment 03
Sdtl assignment 03Sdtl assignment 03
Sdtl assignment 03
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
 
polymorphism.ppt
polymorphism.pptpolymorphism.ppt
polymorphism.ppt
 
Lecture02-OOP-Review.ppt
Lecture02-OOP-Review.pptLecture02-OOP-Review.ppt
Lecture02-OOP-Review.ppt
 

Recently uploaded

BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.PraveenaKalaiselvan1
 
Pests of safflower_Binomics_Identification_Dr.UPR.pdf
Pests of safflower_Binomics_Identification_Dr.UPR.pdfPests of safflower_Binomics_Identification_Dr.UPR.pdf
Pests of safflower_Binomics_Identification_Dr.UPR.pdfPirithiRaju
 
preservation, maintanence and improvement of industrial organism.pptx
preservation, maintanence and improvement of industrial organism.pptxpreservation, maintanence and improvement of industrial organism.pptx
preservation, maintanence and improvement of industrial organism.pptxnoordubaliya2003
 
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)riyaescorts54
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
FREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by naFREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by naJASISJULIANOELYNV
 
Pests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdfPests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdfPirithiRaju
 
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...lizamodels9
 
Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?Patrick Diehl
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfSELF-EXPLANATORY
 
The dark energy paradox leads to a new structure of spacetime.pptx
The dark energy paradox leads to a new structure of spacetime.pptxThe dark energy paradox leads to a new structure of spacetime.pptx
The dark energy paradox leads to a new structure of spacetime.pptxEran Akiva Sinbar
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Nistarini College, Purulia (W.B) India
 
Grafana in space: Monitoring Japan's SLIM moon lander in real time
Grafana in space: Monitoring Japan's SLIM moon lander  in real timeGrafana in space: Monitoring Japan's SLIM moon lander  in real time
Grafana in space: Monitoring Japan's SLIM moon lander in real timeSatoshi NAKAHIRA
 
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxLIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxmalonesandreagweneth
 
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdf
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdfPests of Blackgram, greengram, cowpea_Dr.UPR.pdf
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdfPirithiRaju
 
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)Columbia Weather Systems
 
Sulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptx
Sulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptxSulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptx
Sulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptxnoordubaliya2003
 
GenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptxGenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptxBerniceCayabyab1
 

Recently uploaded (20)

BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
 
Pests of safflower_Binomics_Identification_Dr.UPR.pdf
Pests of safflower_Binomics_Identification_Dr.UPR.pdfPests of safflower_Binomics_Identification_Dr.UPR.pdf
Pests of safflower_Binomics_Identification_Dr.UPR.pdf
 
preservation, maintanence and improvement of industrial organism.pptx
preservation, maintanence and improvement of industrial organism.pptxpreservation, maintanence and improvement of industrial organism.pptx
preservation, maintanence and improvement of industrial organism.pptx
 
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
FREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by naFREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by na
 
Pests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdfPests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdf
 
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
Best Call Girls In Sector 29 Gurgaon❤️8860477959 EscorTs Service In 24/7 Delh...
 
Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
 
The dark energy paradox leads to a new structure of spacetime.pptx
The dark energy paradox leads to a new structure of spacetime.pptxThe dark energy paradox leads to a new structure of spacetime.pptx
The dark energy paradox leads to a new structure of spacetime.pptx
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...
 
Grafana in space: Monitoring Japan's SLIM moon lander in real time
Grafana in space: Monitoring Japan's SLIM moon lander  in real timeGrafana in space: Monitoring Japan's SLIM moon lander  in real time
Grafana in space: Monitoring Japan's SLIM moon lander in real time
 
Volatile Oils Pharmacognosy And Phytochemistry -I
Volatile Oils Pharmacognosy And Phytochemistry -IVolatile Oils Pharmacognosy And Phytochemistry -I
Volatile Oils Pharmacognosy And Phytochemistry -I
 
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort ServiceHot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
 
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxLIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
 
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdf
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdfPests of Blackgram, greengram, cowpea_Dr.UPR.pdf
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdf
 
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
 
Sulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptx
Sulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptxSulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptx
Sulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptx
 
GenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptxGenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptx
 

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