1 advanced programming topics objectives: multithreaded applications thread life cycle thread...

24
1 Advanced Programming Topics Objectives: Multithreaded Applications Thread Life Cycle Thread Scheduling & Synchronization Creating and Using Delegates Events as special Delegates The Standard Event Handler Inheritance Interfaces

Post on 21-Dec-2015

220 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

1

Advanced Programming Topics

Objectives: Multithreaded Applications

Thread Life Cycle Thread Scheduling & Synchronization

Creating and Using Delegates Events as special Delegates The Standard Event Handler

Inheritance Interfaces

Page 2: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

2

Multithreaded Programming

The benefits of multithreaded programming can be broken down into four major categories: Responsiveness Resource sharing Economy Utilization

Page 3: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

3

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);

}}

}

Page 4: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

4

Thread Life Cycle

Page 5: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

5

Thread Scheduling & Synchronization: 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

Page 6: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

6

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());

}

}

Page 7: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

7

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:

Page 8: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

8

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

Page 9: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

9

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());}

}

Page 10: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

10

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

Page 11: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

11

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 methodd += new PrintingDelegate(Writer2);Console.WriteLine();d("Hello There");

//can also point to instance methodConsole.WriteLine();MessageWriter mw = new MessageWriter();d+= new PrintingDelegate(mw.WriteMessage);d("Hello There");

//You can also remove a methodConsole.WriteLine();

d-= new PrintingDelegate(Writer1);

d("Hello There"); } }public class MessageWriter {

public void WriteMessage(String s) {Console.WriteLine("From MessageWriter: "+s); }}

Page 12: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

12

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

Page 13: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

13

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

Page 14: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

14

Events A common application of delegates is in GUI

programming where they are used as call-back methods

That is, a class representing a GUI control such as the Button class will declare a public field for a delegate which it will invoke when the button is clicked

An application that wishes to be notified when the button is clicked will write a method that should be executed when the button is clicked, and use the method to register with the delegate field

When the user clicks the button, the method is automatically executed

Page 15: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

15

Events This procedure will work fine except for one

problem – the delegate field is public This means other classes (other than the Button

class) can invoke the delegate - thus raising a false alarm. In fact, the field can be assigned a new instance by another class – thus canceling any registration to the delegate made by other classes.

To solve this problem, C# introduced the event modifier

If a delegate field is declared with the event modifier, then only the class in which it is declared can invoke it

Page 16: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

16

Events using System;public delegate void EngineMonitor(String s);public class Car { private int currentSpeed = 0; private bool isDead = false; private int maxSpeed; private String name; public event EngineMonitor Exploded = null; public event EngineMonitor AboutToExplod = null; public Car(String name, int maxSpeed){

this.name = name;this.maxSpeed = maxSpeed; }

public void Accelerate(int increment) { if (isDead) {

if (Exploded != null) Exploded("The car has exploded"); }

else { currentSpeed += increment; if (currentSpeed >= maxSpeed) {

isDead = true;if (Exploded != null) Exploded("The car has exploded"); }

else if (currentSpeed + 20 >= maxSpeed && AboutToExplod != null) AboutToExplod("Dangerous Speed:"+currentSpeed+",

Car about to explod"); else Console.WriteLine("Current Speed = "+currentSpeed);

} } }

public class EventExample {public static void Main() { Car myCar = new Car("Corola", 200);

//register with event source myCar.Exploded += new EngineMonitor(OnExplod); myCar.AboutToExplod += new EngineMonitor(OnAboutToExplod);

//speed up for (int i=0; i<10; i++) myCar.Accelerate(20);

//cancel registration to events myCar.Exploded -= new EngineMonitor(OnExplod); myCar.AboutToExplod -= new EngineMonitor(OnAboutToExplod);

//no response for (int i=0; i<10; i++) myCar.Accelerate(20); } public static void OnExplod(String s) { Console.WriteLine("Message from car: "+s); }

public static void OnAboutToExplod(String s) { Console.WriteLine("Message from car: "+s); }}

Page 17: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

17

The Standard Event Handler Because the use of delegates to handle events is

very common in GUI programming, C# has defined a special delegate named, EventHandler, which is used by most control classes to handle events

However, the EventArgs class is a class that does not have any fields that can be used to pass the event information to the client

If there is a need to send event information, the programmer is expected to create a sub class from EventArgs, in which the desired fields and methods can be defined

Page 18: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

18

using System;public class EventMessage : EventArgs { private string message; public EventMessage(string msg) {

message = msg; } public string Message {

get {return message;} } }public class Car { private int currentSpeed = 0; private bool isDead = false; private int maxSpeed; private String name;

public event EventHandler Exploded = null; public event EventHandler AboutToExplod = null;

public Car(String name, int maxSpeed){ this.name = name; this.maxSpeed = maxSpeed;} public void Accelerate(int increment) { if (isDead) { if (Exploded != null) Exploded(this, new EventMessage("The car has exploded")); } else { currentSpeed += increment; if (currentSpeed >= maxSpeed) { isDead = true; if (Exploded != null) Exploded(this, new EventMessage("The car has exploded")); } else if (currentSpeed + 20 >= maxSpeed && AboutToExplod != null)

AboutToExplod(this, new EventMessage("Dangerous Speed:"+ currentSpeed+", Car about to explod")) else

Console.WriteLine("Current Speed = "+currentSpeed); } } }

public class EventExample {public static void Main() { Car myCar = new Car("Corola", 200);

//register with event source myCar.Exploded += new EventHandler(OnExplod); myCar.AboutToExplod += new EventHandler(OnAboutToExplod);

//speed up for (int i=0; i<10; i++) myCar.Accelerate(20);

//cancel registration to events myCar.Exploded -= new EventHandler(OnExplod); myCar.AboutToExplod -= new EventHandler(OnAboutToExplod);

//no response for (int i=0; i<10; i++) myCar.Accelerate(20); }

public static void OnExplod(Object source, EventArgs e) { Console.WriteLine("Message from car: " +((EventMessage)e).Message); }

public static void OnAboutToExplod(Object source, EventArgs e) { Console.WriteLine("Message from car: "+((EventMessage)e).Message); } }

Page 19: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

19

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.

Page 20: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

20

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

Page 21: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

21

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(. . .) {. . .

} } 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.

Page 22: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

22

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

}}

http://www.c-sharpcorner.com/Code/2002/Sept/ImplInherit.asp

Page 23: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

23

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

Page 24: 1 Advanced Programming Topics Objectives:  Multithreaded Applications  Thread Life Cycle  Thread Scheduling & Synchronization  Creating and Using Delegates

24

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