Using delegates and Events 2 (from a 49 $/817 Page 2002 Year Book "C#.net Web Developers Guide")

Source: Internet
Author: User
Tags constructor datetime flush log message queue
Guid|web Figure 2.8 continued
continued.78 Chapter 2 Introducing C # programming
Appears in the message queue. Notice the signature matches
That requried by Addeventcallback
public void Logaddrequest (string FirstName, String LastName,
String middlename, String SSN)
{
String name = FirstName + "" + MiddleName + "" + LastName;
FileStream stream = new FileStream (M_filename,
FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter writer = new StreamWriter (stream);
Writer. Basestream.seek (0, Seekorigin.end);
Writer. Write ("{0} {1} \ n", DateTime.Now.ToLongTimeString (),
DateTime.Now.ToLongDateString ());
Writer. Write ("adding Employee-name: {0}, SSN: {1}",
Name, SSN);
Writer. Write ("\ n------------------------------------\ n \ nplease");
Writer. Flush ();
Writer. Close ();
}
}
A new class, Employeequeuelogger, has been added. It has a method
Logaddrequest, which logs requests to add employees to a log file. The important
Thing to the Logaddrequest method has a signature that matches the
Addeventcallback delegate signature. An instance of the logger is created in the
constructor of Employeequeuemonitor. The code that wires up the delegates is also
In the constructor and are shown here:
M_logger = new Employeequeuelogger ("Log.txt");
M_addeventcallback = new Addeventcallback (this.addemployee);
M_addeventcallback + = new Addeventcallback (
M_logger.logaddrequest);
Http://www.syngress.com
Figure 2.8 continued.introducing C # programming Chapter 2 79
A new logger instance is created. Next, the delegate is initialized with a
The callback function to the AddEmployee method of Employeequeuemonitor.
Finally, a second callback is added to the delegate, which'll invoke the
Logaddrequest of the Employeequeuelogger class. Notice that's plus sign is used
To add the second callback to the delegate. The plus sign (addition operator) has
been overloaded in the System.Delegate class of the. NET Framework to call the
Combine method of this class. The Combine method adds the callback to the list of
Methods the delegate maintains. The minus sign (subtraction operator) is also
Overloaded to call the Remove method, which removes a callback from the list of
Methods the delegate maintains. The rest of the source code remains unchanged.
When the delegate are invoked in the Start method of Employeequeuemonitor, both
Employeequeuemonitor.addemployee and Employeequeuelogger.logaddrequest are
Executed.
Events
The event model is often referred to as the Publish/subscribe model or the listener
Pattern. The idea behind the event model are that a class publishes the events that it
Can raise. Consumers of the class object subscribe to the events they are interested
In. When the event occurs, the "object" monitors the event notifies all Sub-scribers
That event has been raised. The subscribers then take some action.
The event model is often used in GUI programs. Handlers are set up for
Common events, such as pressing a button. When the button press event occurs,
All Subscribers registered for the button press event are invoked. The. NET
Framework uses the event model and particular the System.event delegate for
Windows forms–based applications.
The. NET Framework supplies a built in delegate of type System.event. The
Idea of events in the the. NET Framework are to supply a single signature for the Del-egate
Regardless of the "data" is passed to the subscribed callback. One of the
Arguments for the Event delegate is a object derived from the. NET Framework
Class System.EventArgs, which contains the data the callback needs. You declare a
Class derived from System.EventArgs with the data your callback needs. When the
Event takes place, where you instantiate your derived EventArgs object and invoke the
Event. Callback functions subscribed to the event are called passing the object
Derived from EventArgs. Changes to the multicast Delegate code sample that
Implement events are shown in Figure 2.9.The full source code for this sample is
On the CD in the file Events.cs.
http://www.syngress.com.80 Chapter 2 Introducing C # programming
Figure 2.9 Relevant portions of the Events.cs program Listing
<summary>
Defines the data that would be passed from the event delegate to
The callback method when the event is raised
</summary>
Class Addemployeeventargs:eventargs
{
String M_firstname;
String M_lastname;
String M_middlename;
String m_ssn;
Public Addemployeeventargs (String FirstName,
String LastName, String middlename, String SSN)
{
M_firstname = FirstName;
M_lastname = LastName;
M_middlename = MiddleName;
M_SSN = SSN;
}
Event argument properties contain the data to pass to the
Callback methods subscribed to the event.
public string FirstName {get {return m_firstname;}}
public string LastName {get {return m_lastname;}}
public string MiddleName {get {return m_middlename;}}
public string SSN {get {m_ssn;}}
}
<summary>
Simulates monitoring a message queue. When a message appears
The event is raised and methods subscribed to the event
are invoked.
</summary>
Http://www.syngress.com
Continued.introducing C # programming Chapter 2 81
Class Employeequeuemonitor
{
Event Signature for Addemployeeevent
public delegate void Addemployeeevent (object sender,
Addemployeeventargs e);
Instance of the Addemployeeevent
public event Addemployeeevent Onaddemployee;
Private Employeequeuelogger M_logger;
Private Employees m_employees;
private int m_lengthqueue;
Private string[,] M_msgqueue =
{
{"Timothy", "Arthur", "Tucker", "555-55-5555"},
{"Sally", "Bess", "Jones", "666-66-6666"},
{"Jeff", "Michael", "Simms", "777-77-7777"},
{"Janice", "Anne", "Best", "888-88-8888"}
};
Public Employeequeuemonitor (Employees Employees)
{
M_employees = employees;
M_lengthqueue = 4;
M_logger = new Employeequeuelogger ("Log.txt");
Register the methods that the Event would invoke when a add
Employee message are read from the message queue
Onaddemployee =
New Addemployeeevent (This.addemployee);
Http://www.syngress.com
Figure 2.9 continued
continued.82 Chapter 2 Introducing C # programming
Onaddemployee =
New Addemployeeevent (m_logger.logaddrequest);
}
Drain the queue.
public void Start ()
{
if (m_employees = null)
Return
for (int i = 0; i < m_lengthqueue; i++)
{
Pop an Add employee request off the queue
String FirstName = m_msgqueue[i,0];
String middlename = m_msgqueue[i,1];
String LastName = m_msgqueue[i,2];
String SSN = m_msgqueue[i,3];
Console.WriteLine ("Invoking Delegate");
Create the event arguments to the methods
Subscribed to the event and then invoke event resulting
In the callbacks methods being executed, namely
Employees.this.addEmployee () and
Employeequeuelogger.logaddrequest ()
Addemployeeventargs args = new Addemployeeventargs (FirstName,
LastName, MiddleName, SSN);
Onaddemployee (this, args);
}
}
public void Stop ()
{
Http://www.syngress.com
Figure 2.9 continued
Continued.introducing C # Programming Chapter 2 83
In a real communications program your would shut down
Gracefully.
}
Called by event whenever a new Add employee message appears
In the message queue. Notice the signature matches that required
by system.event
public void AddEmployee (object sender, Addemployeeventargs e)
{
Console.WriteLine ("In delegate, adding employee\r\n");
int index = m_employees. Length;
M_employees[index] = new Employee (E.firstname, E.middlename,
E.lastname, E.SSN);
}
}
<summary>
Writes add employee events to a log file.
</summary>
Class Employeequeuelogger
{
String M_filename;
Public Employeequeuelogger (String fileName)
{
M_filename = FileName;
}
Called by event whenever a new Add employee message appears
In the message queue. Notice the signature matches that required
by system.event
public void Logaddrequest (object sender, Addemployeeventargs e)
Http://www.syngress.com
Figure 2.9 continued
continued.84 Chapter 2 Introducing C # programming
{
String name = E.firstname + "" + E.middlename + "" +
E.lastname;
FileStream stream = new FileStream (M_filename,
FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter writer = new StreamWriter (stream);
Writer. Basestream.seek (0, Seekorigin.end);
Writer. Write ("{0} {1} \ n", DateTime.Now.ToLongTimeString (),
DateTime.Now.ToLongDateString ());
Writer. Write ("adding Employee-name: {0}, SSN: {1}",
Name, E.SSN);
Writer. Write ("\ n------------------------------------\ n \ nplease");
Writer. Flush ();
Writer. Close ();
}
}
A new class, Addemployeeventargs, has been added. It contains the Informa-tion
That would be passed to callback methods subscribed to the event. Notice the
Data members of the Addemployeeventargs class are the same as the signature for
The Addeventcallback delegate in our previous sample. Instead of invoking the
Callback with individual arguments, while using events, you pass a class object,
which contains the arguments instead.
Just As with the delegates samples, we declare the signature and create a
Member variable to the delegate in Employeequeuemonitor class. The only Differ-ence
Is that the signature matches the signature necessary for events. The
Parameter is the "object" raised the event, and the second is the object instance
That's contains the arguments passed to subscribed callback methods. This is shown
Here
public delegate void Addemployeeevent (object sender,
Http://www.syngress.com
Figure 2.9 continued.introducing C # programming Chapter 2 85
Addemployeeventargs e);
public event Addemployeeevent Onaddemployee;
In the constructor of the class, we subscribe the callback methods to the
Event as shown here:
Onaddemployee =
New Addemployeeevent (This.addemployee);
Onaddemployee =
New Addemployeeevent (m_logger.logaddrequest);
The callback methods have the correct signature for event callbacks. Here are
The callback method ' s signatures:
public void AddEmployee (object sender, Addemployeeventargs e)
public void Logaddrequest (object sender, Addemployeeventargs e)
When a add employee message was popped off the ' queue in the ' Start method
Of Employeequeuemonitor, an instance of the Addemployeeeventargs is created and
The event is invoked. Here's the code that accomplishes this:
Addemployeeventargs args = new Addemployeeventargs (FirstName,
LastName, MiddleName, SSN);
Onaddemployee (this, args);
As you can, using the events instead of delegates is really just a syntactic dif-ference.
The code is nearly identical. The main benefit is this you don ' t have a
Different delegate signature for every delegate your create based on the data this is
Passed to subscribed callbacks. Instead, the standard event delegate signature would
Suffice.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.