What are Events:
Events
are variables of Type delegate.
Events
enable a class or an object to notify other classes or objects when something
of interest occurs. They enable these classes or objects to communicate.
The class
that sends or raises the event is called the Publisher.
The class
that receive or handle the event are called subscribers.
One class
can raise the event to multiple subscribers.
The glue
between the event and the methods to be executed are the delegates. The event
must internally store a "list" of pointers to the methods to call
when the event is raised.
We use
the delegate as the "contract" between the event and all the specific
methods that will be called.
Invoking
an event can only be done from within the class that declared the event.
An event
handler signature, that is the return type and the number and types of
arguments it takes, is determined by the signature of the delegate used to
define the event.
Typically,
you would not expect to return a value from an event handler as a function
return value because an event can have multiple subscribers and each would be
returning a return value independently of the other handlers and would require
special event firing code to decide what to do with all the return values.
Typically,
if you need to communicate back from an event handler the EventArgs structure
would contain members that the handler can update and each handler will get an opportunity
to look at the values and update accordingly, and the code firing the event
only needs to react to the final value in the structure.
One use
of Events is that we do not need to change the original publisher class again
and again…. We can simply add the logic to any of the subscriber class without
changing the publisher class. Hence the Publisher class doesn’t need
recompilation and redeployment i.e. by this we can add more capabilities.
The main purpose of events is to prevent
subscribers from interfering with one another.
Events are an abstraction over top of the
delegates that makes them safe to expose from a class i.e. with Events, we can
only add or remove our entries to the delegate’s method invocation list, hence
we cannot tamper with anyone else’s invocation list inside of that delegate.
// Delegate definition
public delegate void PriceChangedHandler
(decimal oldPrice,decimal newPrice);
public class Broadcaster
{
// Event declaration
public event PriceChangedHandler
PriceChanged;
}
Code within the Broadcaster type has full
access to PriceChanged and can treat it
as a delegate. Code outside of Broadcaster
can only perform += and -= operations
on the
PriceChanged event.
Subscribers could do the following things
to interfere with each other:
• Replace other subscribers by reassigning
Delegate (instead of using the += operator).
• Clear all subscribers (by setting
Delegate to null).
•
Broadcast to other subscribers by invoking the delegate.
Declaring
the event keyword prevents any of the delegate’s users from setting it to null.
In
conclusion: an event declaration adds a layer of protection on the delegate
instance. This protection prevents clients of the delegate from resetting the
delegate and its invocation list, and only allows adding or removing targets
from the invocation list
The
following shows the basic syntax for declaring an event:
accessibility event delegate EventName;
Here, delegate
is: A delegate type that defines the kind of
method that can act as an event handler for the event.
For
example, the BankAccount class
might use the following code to define the Overdrawn
event:
public delegate void
OverdrawnEventHandler();
public event OverdrawnEventHandler
Overdrawn;
The first
line declares the OverdrawnEventHandler
delegate,
which represents methods that take no parameters and that return void.
The
second line declares an event named Overdrawn
that
has the type OverdrawnEventHandler. That
means subscribers must use a method that matches the OverdrawnEventHandler delegate
to catch the event.
Events
are a special kind of multicast delegates that can only be invoked from within
the class or struct where they are declared .i.e. the publisher class.
Events have the following
characteristics:
1.
The publisher determines when an event is raised.
2.
The subscriber determines what action is taken in
response to the event.
3.
An event can have multiple subscribers.
4.
A subscriber can handle multiple events from
multiple publishers.
5.
Events are typically used to signal user actions.
6.
Events are based on the EventHandler delegate and
the EventArgs base class.
How Events work:
The publisher creates the event
The subscriber
subscribes to the event i.e. setting a particular method as a target method to
a delegate.
Then the
subscriber creates a handler for the event.
Then when
the publisher raises the Event, the subscriber’s handler is called and the
subscriber takes some action.
Using EventHandlers:
EventHandlers
are just the target methods of the delegate.
The .Net
Framework provides an event that is pre-wired to a delegate. It is called
EventHandler event. so we don’t need to
go to the process of creating the delegate.
//
1.first create a delegate
public delegate void del(string x);
//
2. then create the event of delegate type that is going to publish.
public event del evt;
The event handlers should be like
EventHandler<EventArgs> where EventArgs is class that inherits
from System.EventArgs and in that class you can define additional properties
for the event.
public class MyClass
{
public event
EventHandler<MyEventArgs> CustomEvent;
}
public class MyEventArgs
: EventArgs
{
public string Message { get; private set; }
public MyEventArgs (string msg) : base()
{
this.Message = msg;
}
}
The event
handler should have parameters object and class that inherits from
System.EventArgs, where object is the source (sender) of the event and event
args are the arguments for the event.
private OnCustomEvent(object sender, MyEventArgs e)
{
Console.WriteLine(e.Message);
}
With
lambda expression you can declare event handler much cleaner.
ip.Completed += (sender,
e) =>
{
//your code goes here, which is activated
when your event is triggered
};
'sender'
and 'e' are custom named parameters which are by default 'object' type (sender)
and 'EventArgs' type (e). If you want to use some other type in parameters you
have to ephasize that in parameters.
0 comments:
Post a Comment