PATTERNS06 - The .NET Event Model

30
The .NET Event Model Michael Heron

description

An introduction to the .NET event model. Suitable for intermediate to advanced computing students and those studying software engineering.

Transcript of PATTERNS06 - The .NET Event Model

Page 1: PATTERNS06 - The .NET Event Model

The .NET Event ModelMichael Heron

Page 2: PATTERNS06 - The .NET Event Model

Introduction Event driven programming is a philosophy for

building GUI applications. Most modern programming languages incorporate

a facility for event driven programming. The mechanism by which events can be created

and handled varies from language to language. It tends to be markedly different in OO languages

from non OO languages. For the next few lectures, we are going to be

looking at .NET. Specifically, C#

Page 3: PATTERNS06 - The .NET Event Model

Event Driven Programming – In Brief Console applications are system driven.

The user is just a puppet. The flow of execution is with the computer.

Modern GUI based applications are user driven. The computer is just a puppet. The flow of execution is with the user.

This is reflected in a shift from processing intensive to interaction intensive applications.

Page 4: PATTERNS06 - The .NET Event Model

Process Intensive Interaction is usually limited to prompts for

information. How many of these For how long

Computer does large amounts of processing with relatively few configuration details. Simulations Complex AI routines Batch processing

Page 5: PATTERNS06 - The .NET Event Model

Interaction Intensive User drives the application.

Processing is usually short and focused. Locus of control inverted from the Olden Days.

Focus is on user involvement in the process.

Word processors Games Pretty much any modern GUI application

Requires a new way of building programs.

Page 6: PATTERNS06 - The .NET Event Model

Event Driven Programming In event driven programs, system driven

by user interactions. Click a button Move a scrollbar Type in a textbox

All interactions with a system component generate events. Events contain information regarding the

precise nature of the interaction

Page 7: PATTERNS06 - The .NET Event Model

Event Driven Programming Each GUI component is responsible for

dispatching information on events to interested parties. Usually functions in a program.

Components hold an internal list of listeners. Things that are listening for specific kind of

events. Each listener, or handler, is responsible for

dealing with its response to the event occurring.

Page 8: PATTERNS06 - The .NET Event Model

Event Models – VB (Pre .NET) Listener functions indicated by naming

convention. Function for deal with a click event on a control

called cmdButton was called cmbButton_click. Somewhat limited.

Stuck with predefined naming format. No way for multiple functions to indicate an

interest. No longer the model used for VB in the .NET

framework.

Page 9: PATTERNS06 - The .NET Event Model

Event Models - Java Objects indicate their interest in an event by

marking themselves as a listener. Object oriented structure of the language allows for

each listener to define the handler method. Listeners defined by implementation of an interface

Correct methods indicated by naming convention. actionPerformed for button clicks adjustmentValueChanged for adjustment events

More flexible, but still somewhat clumsy. One single method must manage events from

many different components.

Page 10: PATTERNS06 - The .NET Event Model

Event Models - .NET Components hold a list of delegates.

Each delegate contains a pointer to a function. Direct mapping in .NET from event to delegates.

Delegates act as a wrapper around a function call. Each component can have its own method. Each component can handle multiple different

listeners. This is known as multicasting.

Best model so far?

Page 11: PATTERNS06 - The .NET Event Model

Event Driven Programming and OO The event handler methods called when a

method is fired get specifically configured objects as a parameter. They hold the state information associated

with the event. These all stem from a common OO core

Polymorphism in Java permits compile time checking of event structure.

Delegate structure permits separation of abstraction and implementation.

Page 12: PATTERNS06 - The .NET Event Model

Delegates – The Basics Works like a type safe function pointer.

A variable that acts as an invokeable reference to a function.

Delegates are objects. Wrappers around the function pointer.

They provide a syntactically neat encapsulation of listener status. And can be polymorphically assessed to

ensure compile-time correction.

Page 13: PATTERNS06 - The .NET Event Model

Delegates in Actionusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

namespace ConsoleApplication3{ public delegate int HandleArithmetic (int num1, int num2);

class Program { public static int addTwoNumbers(int num1, int num2) { return num1 + num2; }

public static int multiplyTwoNumbers(int num1, int num2) { return num1 * num2; }

static void Main(string[] args) { HandleArithmetic adding =new HandleArithmetic(addTwoNumbers); HandleArithmetic multiplying = new HandleArithmetic(multiplyTwoNumbers);

Console.Out.WriteLine("Delegate one = " + adding(10, 20)); Console.Out.WriteLine("Delegate two = " + multiplying (10, 20));

Console.ReadLine();

} }}

Page 14: PATTERNS06 - The .NET Event Model

Delegates – The Basics Delegates allow for the implementation

of a syntactically safe callback. Works on the Hollywood Principle

When attached to an event, they let us define a function stub that is called when specific processes are started / finished

Ideal mechanism for safely handling event invocation.

Page 15: PATTERNS06 - The .NET Event Model

Delegates – For Reals Delegates are just a mechanism used

for .NET event handling. That’s not all they are.

You can think of a delegate as a combination of an object/method reference, and potentially a reference to another delegate. Chain of command pattern. Will invoke the next element in a chain when

one exists.

Page 16: PATTERNS06 - The .NET Event Model

Delegates – For Reals Small performance overhead associated

with delegates. Not as much as it used to be

Considerable leeway given for compile-time optimization. This is a consequence of the very strict

rules governing delegate construction.

Page 17: PATTERNS06 - The .NET Event Model

Delegates Delegates get added directly to the

event type of the component. Delegates are usually an instance of the

EventHandler class Most of this is handled automatically for

you in Visual Studio .NET:

this.cmdButton.Click += new System.EventHandler (this.HandleClick)

Page 18: PATTERNS06 - The .NET Event Model

The Structure of Events in .NET Different terminology is used here.

Consumer and Producer Dispatcher and Listener Publisher and Subscriber

The core of the idea is that we completely separate out event dispatch and event handling. This is the best way to handle coupling

between objects.

Page 19: PATTERNS06 - The .NET Event Model

Event Handler Event Handlers have a very simple

interface. One parameter represents the source of

the event The second represents state information.

All objects in .NET extend from a class called object. Polymorphism allows us to use that to

deal with event dispatch references.public void Handle_Click (object sender, EventArgs e) {}

Page 20: PATTERNS06 - The .NET Event Model

Benefits of Separation Communication between objects without hard-

coded associations. Ensures cleanness of communication by virtue of

polymorphic interfaces. We know that we just need to deal with an event

object in our handler function. Scalable without adding complexity.

Each component manages its own dispatching. Extensible

We can easily add in our own events More on this in the next lecture

Page 21: PATTERNS06 - The .NET Event Model

Benefits of the Delegate Model One of the benefits of the delegate model

is that it allows new handlers to be instantiated at runtime. Not possible in either Java or old versions of

.NET Handlers can be dynamically added or

removed while the program is running. Allowing for a very clean and efficient

implementation of dynamic delegate dispatching.

Page 22: PATTERNS06 - The .NET Event Model

Back to Design Patterns… You may find this event dispatch/handler

method referred to in the literature. It’s known as the observer design pattern.

It has pretty wide applicability. Many languages use the observer patter in one

way or another. To add an extra level of complexity, the event

dispatch is often handled external. Objects indicate they wish to dispatch an event. The event dispatch thread handles the hard work.

Page 23: PATTERNS06 - The .NET Event Model

Java Events The event model used within Java is the

delegation model. Objects are broken into two categories:

Event handlers Event dispatchers

The event dispatcher is responsible for informing all interested objects when an event occurs.

The event handler executes the code that should be executed when the event occurs.

Page 24: PATTERNS06 - The .NET Event Model

Java Events Imagine if we wanted to trigger our own events. For example, a countdown timer that should call an

event when it hits zero. The clock itself is an event dispatcher.

It has no code for handling the events. It has all the code for ensuring the events get called at the

correct time. Anything that was interested in catching this event

would be an event listener. It doesn’t administer the events, but contains the code

required for implementing the functionality. An event dispatcher may have many handlers.

Page 25: PATTERNS06 - The .NET Event Model

Java Events We can use this same model for

dispatching other kinds of events. For example, we might want an action

event when the clock has finished counting.

We need to add a pair of add and remove methods for the appropriate listener.

We also need a suitable data structure for storing interested objects.

Page 26: PATTERNS06 - The .NET Event Model

Java Events Often, we need nothing more

complicated than an ArrayList to store listener objects.

We need to ensure these methods are thread-safe, which means using the synchronised keyword. Don’t worry too much about this for now.

We may return to this topic later on.

Page 27: PATTERNS06 - The .NET Event Model

Java Events ArrayList<ActionListener> myActionListeners;

public synchronized void addActionListener (ActionListener ob) {

myActionListeners.add(ob); } public synchronized void

removeActionListener (ActionListener ob) { myActionListeners.remove(ob); }

Page 28: PATTERNS06 - The .NET Event Model

Java Events We also need a method that handles calling

the appropriate handler on each object:

public void handleActionEvents() {ActionEvent ex = new ActionEvent (this, 0,

null);ActionListener temp;

for (int i = 0; i < myActionListeners.size(); i++) { temp = myActionListeners.get(i); temp.actionPerformed (ex); }

}

Page 29: PATTERNS06 - The .NET Event Model

Java Events Now we can register an actionListener

on our this hypothetical clock just like we can with a JButton. Except we have to provide the

architecture for handling it ourselves. Provided the handleActionEvents

method gets called at the right time, it’s all Sunshine and Lollypops.

Page 30: PATTERNS06 - The .NET Event Model

Summary Event handling in .NET is done using the

observer pattern. And through the mechanism of delegates

There are several benefits that accrue from this approach. It’s the cleanest way of allowing objects

to communicate. The best kind of coupling.

Delegates are pretty powerful.