Module 11:
Events
By
SRIRAM . B
Overview
Events
What is an event?
How events work?
Defining an event
Handling an event
Events
Events allow an object to notify other objects that a change has
occurred. The other objects can register an interest in an event,
and they will be notified when the event occurs.
How Events work?
Publisher raises an event to alert all interested objects
(subscribers)
Subscriber provides a method to be called when the event is
raised
Defining an event
event mydelegate myevent; (To be declared within the class)
Events
Subscribing to an Event
[Link] = new mydelegate([Link]);
[Link] += new mydelegate(obj.my1);
Notifying
[Link]();
Passing parameters to events
Derive a class from EventArgs
Have the necessary get methods
Create the delegate with 2 parameters one is the
sender and the other is the eventargs
Handling an event
To handle an event we need to subscribe to the
event by providing an event handler function whose
signature matches that of delegate specified for use
with the event.
Example - Events
using System;
using [Link];
namespace events
{
public class EventHandler2
{
static int counter = 0;
static string str = "STG INTERNATIONAL
LIMITED";
public static void WriteChar(object o,
ElapsedEventArgs e)
{
[Link](str[counter++ % [Link]]);
}
Example - Events
static void Main(string[] arg)
{
Timer tm = new Timer(100);
[Link] += new
ElapsedEventHandler(WriteChar);
[Link]();
[Link]();
}
}
}
Session Ends
Exercise
Relax