Tuesday, August 01, 2006

CLR Event Model


The common Language runtime event model is based on delegates.A delegates is a type-safe way to invoke a callback method. Callback methods are the means by which objects receive the notification they subscribed to.
To help you fully understand the way event work within the CLR,I'll start with a secnario in which events are useful.Suppose you want to design an e-mail application.When an e-mail message arrives,the user might like the message to be forwarded to a fax machine or a pager.
In architecting this application,let's say that you'll first design a type,called MailManager,that receives the incoming e-mail message. MailManager will expose an event called NewMail. Oter type(such as Fax and Pager) may register interest in this event. When MailManager receives a new e-mail message,it will raise the event,causing the message to be distributed each of the registered objects.

When the application intializes,let's instantiate just one MailManager instance-the application can then instantiate any number of Fax and Pager Type.Above figure shows how the application initializes and what happen when a new e-mail message arrive.

The application intializes by constructing an instance of MailManager. MailManager offer a NewMail event.When the Fax and Page objects are constructed, they register themselves with MailManager's NewMail event so that MailManager knows to notify the Fax and Pager objects when new e-mail message arrive.

Step # 1 : Define a type that will hold any additional information that should be sent to receivers of the event notification

internal class NewMailEventArgs : EventAgrs
{
private readonly string m_from,m_to,m_subject;
public NewMailEventArgs(string from,string to,string subject)
{
m_from = from;
m_to = to
m_subject = subject;
}

public string from
{
get
{
}
return m_from;
}

public string To
{
get
{
}
return m_to;
}

public string Subject
{
get
{
}
return m_subject;
}


Step # 2 :Define Event member

internal class MailManager
{
publiuc event Eventhandler NewMail;
......
}

Step # 3: Define a method responsible for raising the event to notify registered objects that the event has occured

internal class MailManager
{
protected virtual void onNewMail(NewMailEventArgs e)
{
EventHandler temp = NewMail;
if(temp != null)
{
temp(this,e);
}
}
}

Step #4 : Define a method that translates the input into the desired event

internal class MailManager
{
public void SimulateNewMail (string from,string to,string subject)
{
NewMailEventArgs e = new NewMailEventArgs(from,to,subject);
onNewMail(e);
}
}


Designing a Type That Listen for an Event

internal class Fax
{
public Fax(MailManager mm)
{
mm.NewMail += FaxMsg;
}

private void FaxMsg(object sender, NewMailEventArgs e)
{
Console.writeLine("From{0} , To{1}, Subject{2}", e,from,e.to,e.Subject);
}

public void Unregister(MailManager mm)
{
mm -= FaxMsg;
}

}