1.NETDelegates & eventsNOEA / PQC 2007 Delegates & events Observer pattern Delegates –Semantics –Cil – code –Usage Events Asynchronious delegates.

Slides:



Advertisements
Similar presentations
Generalized Requests. The current definition They are defined in MPI 2 under the hood of the chapter 8 (External Interfaces) Page 166 line 16 The objective.
Advertisements

Ch 7 B.
C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Written by: Dr. JJ Shepherd
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Objects and Classes First Programming Concepts. 14/10/2004Lecture 1a: Introduction 2 Fundamental Concepts object class method parameter data type.
Delegates and Events Tom Roeder CS fa. Motivation – Function Pointers Treat functions as first-class objects eg. Scheme: (map myfunc somelist)
Event Notification Pattern Dr. Neal CIS 480. Event Notification Pattern When a class abc has something happening that class xyz needs to know about you.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
Programming Languages and Paradigms Object-Oriented Programming.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Web Services Week 2 Aims: Getting started with creating simple C# applications within Visual Studio.NET Objectives: –An introduction to the syntax of C#.NET.
CSC 313 – Advanced Programming Topics. Observer Pattern Intent  Efficiently perform 1-to-many communication  Easy to respond dynamically when event(s)
The Java Programming Language
Basic Java Syntax CSE301 University of Sunderland Harry R Erwin, PhD.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Delegates Programming in C# Delegates CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
1 Web Based Programming Section 8 James King 12 August 2003.
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
ADVANCED WEB SERVICES. Three Advanced Web Service Techniques SOAP Extensions Asynchronous calls Custom wire formatting SOAP Extensions Asynchronous calls.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
Concurrent Programming and Threads Threads Blocking a User Interface.
CSC 313 – Advanced Programming Topics. Observer Pattern in Java  Java ♥ Observer Pattern & uses everywhere  Find pattern in JButton & ActionListener.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
Java Thread and Memory Model
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
1 Software Construction and Evolution - CSSE 375 Exception Handling – Chaining & Threading Steve Chenoweth Office: Moench Room F220 Phone: (812)
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
FEN 2014UCN Teknologi/act2learn1 Higher order functions Observer Pattern Delegates Events Visitor Pattern Lambdas and closures Lambdas in libraries.
Multi-Threading in Java
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1.NETDelegates & eventsNOEA / PQC Delegates & events Observer pattern Delegates –Semantics –Cil – kode –Anvendelse Events.
1 Design Patterns Delegates Visitor Pattern. 2 Observer Pattern Observer Pattern is an object-oriented design that simulates void-pointers in for instance.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 32 JavaBeans and Bean.
Written by: Dr. JJ Shepherd
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
1.NETDelegates & eventsNOEA / PQC 2007 Delegates & events Observer pattern Delegates –Semantics –Cil – kode –Anvendelse Events.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Mid-Year Review. Coding Problems In general, solve the coding problems by doing it piece by piece. Makes it easier to think about Break parts of code.
CIS NET Applications1 Chapter 7 – Asynchronous Calls.
Catalog of Refactoring (6) Making Method Calls Simpler.
Segments Introduction: slides minutes
C# for C++ Programmers 1.
Objects as a programming concept
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2002
Java Programming Language
Delegates and Events 14: Delegates and Events
Methods Attributes Method Modifiers ‘static’
C Basics.
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2005
CS360 Windows Programming
Threads Chate Patanothai.
C# Event Processing Model
null, true, and false are also reserved.
6 Delegate and Lambda Expressions
Introduction to Event Handling
Asynchronous Programming
Delegates & Events 1.
Android Topics Asynchronous Callsbacks
Chapter 15 Multithreading
Chengyu Sun California State University, Los Angeles
Day 11 The Last Week!.
Threads and concurrency / Safety
Presentation transcript:

1.NETDelegates & eventsNOEA / PQC 2007 Delegates & events Observer pattern Delegates –Semantics –Cil – code –Usage Events Asynchronious delegates

2.NETDelegates & eventsNOEA / PQC 2007 An example (from java!) public class FrameMedKnap extends javax.swing.JFrame { private javax.swing.JButton jButton1; public FrameMedKnap() { jButton1 = new javax.swing.JButton(); jButton1.setText("jButton1"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); this.add(jButton1, java.awt.BorderLayout.CENTER); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jButton1.setText("Der er trykket på knap"); }

3.NETDelegates & eventsNOEA / PQC 2007 Observer pattern Also called Observable in some litterature Might also be a interface

4.NETDelegates & eventsNOEA / PQC 2007 Callback interfaces Interfaces describes a common behavior that is shared by different classes Used in Observer pattern to construct a callback mecanism –The key is the Update() method in the Observer interface. –Note that it do not have to be named Update ;-) Callback can be used in languages that supports interfaces Callback can be implemented with function pointers in C (But then it is not by using observer pattern)

5.NETDelegates & eventsNOEA / PQC 2007 Subject (or Observable) implements an add and a remove method to add and remove observers to/from an internal container (typical an arraylist) Has also a notify() method that calls update() on all observer object in the container Observer implements the update() method. That will be the event handler in an event based system What is what in the java example?

6.NETDelegates & eventsNOEA / PQC 2007 Delegate Delegate is a new language construction in C# Java programmers will compare it to observer pattern C/C++, Pascal/Delphi… programmers will compare it to function pointers A delegate gives the possibility to pass a method of a class as a parameter to objects of another class. The method can be a static or an instance method Delegates are object oriented, typesafe and undependent of method name. Delegates are objects itselves of classes that iniherit from System.Delegate via System.MulticastDelegate

7.NETDelegates & eventsNOEA / PQC 2007

8 4 steps to create and use delegates 1.Declare a delegate with a appropiate signature 2.Define method(s) with the same signature 3.Instantiate a delegate object with a method as parameter The method will be encapsulated in the delegate 4.Call the method by the delegate

9.NETDelegates & eventsNOEA / PQC 2007 Step 1: 1.Declare a delegate with a appropiate signature. That means with the same parameters and return values as the method to be encapsulated delegate void Notifier(string sender);

10.NETDelegates & eventsNOEA / PQC 2007 Step 2: Define method with the same signature as the delegate void SayHello (string sender) { Console.WriteLine("Hello from "+ sender); } void SayGoodBye (string sender) { Console.WriteLine("Good Bye from "+ sender); }

11.NETDelegates & eventsNOEA / PQC 2007 Step 3: Instantiate the delegate object and add the methods Notifier notify = new Notifier(SayHello); //Instantiate delegate and thereby a container notify += new Notifier(SayGoodBye); //Add a new Notifier to the container (multicast); //For the example: remove Notifier: notify -= new Notifier(SayHello);

12.NETDelegates & eventsNOEA / PQC 2007 Trin 4: Call the methods via the delegate: notify ("Pingo");

13.NETDelegates & eventsNOEA / PQC 2007 Break opgave Implement a Watch class The time must be updated every second –Use Thread.Sleep(1000) or Thread.CurrentThread.Join(1000) for suspending the program in one second –The time may be updated with _currentTime =_currentTime.AddSeconds(1f); eller _currentTime=DateTime.Now; It must be possible to be notified when the time is updated. Make console application that continuously shows the time

14.NETDelegates & eventsNOEA / PQC 2007 Parallel programming Asynchronous delegates –BeginInvoke and EndInvoke –CallBack

15.NETDelegates & eventsNOEA / PQC 2007 WaitingClass (used as example for delegates) class WaitingClass { private double Wait(int id, int secs) { DateTime t1, t2; TimeSpan dt; Console.WriteLine("Wait ({0}): The time is {1:mm.ss}. Waits for {2} secs", id, t1 = DateTime.Now, secs); Thread.Sleep(1000 * secs); t2 = DateTime.Now; dt = t2 - t1; Console.WriteLine("Wait ({0}): The time {1:mm.ss}. Waited for {2:0.0000} secs", id, t2, dt.TotalSeconds); return dt.TotalSeconds; } continue....

16.NETDelegates & eventsNOEA / PQC 2007 WaitingClass continued public double Wait2(int secs) { Console.WriteLine("Wait2 runs in thread: {0}", Thread.CurrentThread.GetHashCode()); secs = 2 * secs; return Wait(2, secs); } public double Wait1(int secs) { Console.WriteLine("Wait1 runs in thread: {0}", Thread.CurrentThread.GetHashCode()); return Wait(1, secs); }

17.NETDelegates & eventsNOEA / PQC 2007 The WaitDelegate Here: Declared outside the class public delegate double WaitDelegate(int secs);

18.NETDelegates & eventsNOEA / PQC 2007 Synchronious delegate Console.WriteLine("Synchronious delegate"); WaitingClass v = new WaitingClass(); WaitDelegate WaitDelegate = new WaitDelegate(v.Wait1); WaitDelegate += new WaitDelegate(v.Wait2); DateTime t1 = DateTime.Now; WaitDelegate(2); DateTime t2 = DateTime.Now; Console.WriteLine("Time was {0}", ((TimeSpan)(t2 - t1)).TotalSeconds); Thread.Sleep is not precise

19.NETDelegates & eventsNOEA / PQC 2007 Synchronious delegate The methods are executed in the same thread The total execution time is the sum of the execution time for each method. Thread.CurrentThread gives a reference to the active thread myThread.GetHashCode() gives an id for the thread Thread.Sleep(int milliSecs) puts the thread in sleep state for a number of milli seconds. But it depends on the OS' thread controlling

20.NETDelegates & eventsNOEA / PQC 2007 Asynchronious delegate A asynchronious delegate starts with BeginInvoke(....) BeginInvoke's signature is: IAsyncResult BeginInvoke(delegate signatur, AsyncCallback, Object) Get the return value with EndInvoke. EndInvoke's signature is: delegate retur EndInvoke(evt. delegate ref and out, IAsyncResult) BeginInvoke and EndInvoke are 'implemented' at compile time. They are badly documented and depends on the compiler But asynchronious delegates are a easy and pretty safe way to start a thread.

21.NETDelegates & eventsNOEA / PQC 2007 Example 1: BeginInvoke and EndInvoke Console.WriteLine("\nASynchronios delegate 1: EndInvoke without condition"); WaitingClass v = new WaitingClass(); WaitDelegate waitDelegate1 = new WaitDelegate(v.Wait1); WaitDelegate waitDelegate2 = new WaitDelegate(v.Wait2); DateTime t1 = DateTime.Now; IAsyncResult iaResult1 = waitDelegate1.BeginInvoke(2, null, null); IAsyncResult iaResult2 = waitDelegate2.BeginInvoke(2, null, null); double vt1 = waitDelegate1.EndInvoke(iaResult1); double vt2 = waitDelegate2.EndInvoke(iaResult2); DateTime t2 = DateTime.Now; Console.WriteLine("Wait1 waited {0} secs, Wait2 waited {1} secs. Total time was {2}", vt1, vt2, ((TimeSpan)(t2 - t1)).TotalSeconds); EndInvoke blocks Main's thread

22.NETDelegates & eventsNOEA / PQC 2007 Example 2: IsComplete - avoid that EndInvoke blocks... DateTime t1 = DateTime.Now; IAsyncResult iaResult1 = waitDelegate1.BeginInvoke(2, null, null); IAsyncResult iaResult2 = waitDelegate2.BeginInvoke(2, null, null); while (!iaResult1.IsCompleted && !iaResult2.IsCompleted) { Console.Write("."); Thread.Sleep(100); } Console.WriteLine(); double vt1 = waitDelegate1.EndInvoke(iaResult1); double vt2 = waitDelegate2.EndInvoke(iaResult2); DateTime t2 = DateTime.Now; Console.WriteLine("Wait1 waited {0} secs, Wait2 waited {1} secs. Total time was {2}", vt1, vt2, ((TimeSpan)(t2 - t1)).TotalSeconds);

23.NETDelegates & eventsNOEA / PQC 2007 Result Working

24.NETDelegates & eventsNOEA / PQC 2007 Example 3: With WaitOne Makes it possible to handle timeout Console.WriteLine("\nASynchronios delegate 3: EndInvoke with WaitOne condition"); DateTime t1 = DateTime.Now; IAsyncResult iaResult1 = waitDelegate1.BeginInvoke(2, null, null); IAsyncResult iaResult2 = waitDelegate2.BeginInvoke(2, null, null); while (!iaResult1.AsyncWaitHandle.WaitOne(100, true) && !iaResult2.AsyncWaitHandle.WaitOne(100, true)) { Console.Write("."); } double vt1 = waitDelegate1.EndInvoke(iaResult1); double vt2 = waitDelegate2.EndInvoke(iaResult2); DateTime t2 = DateTime.Now; Waits 100 milli seconds for each WaitOne If the method are finish within the time, true is returned else false Note that boolean expression in C# are 'shorting out', meaning that the first part of an AND is false, then the second is not checked. Similary is the second part of OR not checked if the first part is true

25.NETDelegates & eventsNOEA / PQC 2007 Example 4: Callback Avoid the loop.... WaitingClass v = new WaitingClass(); WaitDelegate waitDelegate1 = new WaitDelegate(v.Wait1); WaitDelegate waitDelegate2 = new WaitDelegate(v.Wait2); DateTime t1 = DateTime.Now; IAsyncResult iaResult1 = waitDelegate1.BeginInvoke(2, v.WaitComplete, t1); IAsyncResult iaResult2 = waitDelegate2.BeginInvoke(2, v.WaitComplete, t1); DateTime t2 = DateTime.Now; public void WaitComplete(IAsyncResult IAResult) { Console.WriteLine("WaitComplete runs in thread {0}", Thread.CurrentThread.GetHashCode()); Console.WriteLine("WaitComplete: Waited for {0:0.0000} secs", ((TimeSpan)(DateTime.Now - (DateTime)IAResult.AsyncState)).TotalSeconds); System.Runtime.Remoting.Messaging.AsyncResult ar=(System.Runtime.Remoting.Messaging.AsyncResult) IAResult; WaitDelegate ventDelegate =(WaitDelegate) ar.AsyncDelegate; Console.WriteLine("Return value is: "+ventDelegate.EndInvoke(IAResult).ToString()); } Callback method Status object Here: time before Get the status object An IAsyncResult object shall be passed Get the delegate Call EndInvoke to get a return value

26.NETDelegates & eventsNOEA / PQC 2007 Result: