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

Source: Internet
Author: User
Tags extend log message queue
Guid|web Using delegates and Events
If you are are familiar with Windows programming, your ' ve most likely dealt with
Callbacks. Callbacks are method calls this are executed when some event happens
http://www.syngress.com.70 Chapter 2 Introducing C # programming
During processing. For instance, a callback can is established to handle the pro-cessing
An incoming message on a communications port. Another part of the
Communications program can, messages on a communications port and
Invoke the callback whenever a new message arrives. Function Pointers Perform
The same sort of tasks in straight C + + programs.
Delegates in C # improve on method callbacks in two areas. Delegates are type
Safe, unlike callbacks in Windows programming. In addition, delegates can call
More than one callback the event occurs. This is termed multicasting.
Delegates
Let ' s extend we employees sample to use delegates. This sample simulates a Back-ground
process that receives messages to add new employees to the employee list.
Our queue would be a static array, but in the real world it could is a message
Queue (Microsoft message Queue [MSMQ]), a socket, or some other type of
Queue. The source code in Figure 2.7 shows the relevant portions of the sample
pertaining to delegates. The full source code for this sample is on the CD in the
File Delegates.cs.
Figure 2.7 Relevant portions of the Delegates.cs program Listing
Using System;
Using System.Collections;
<summary>
Contains The program entry the Delegates Sample.
</summary>
Class Delegatessample
{
static void Main (string[] args)
{
Try
{
Create a container to hold employees
Employees Employees = new Employees (4);
Create and drain our simulated message queue
Employeequeuemonitor monitor =
Http://www.syngress.com
Continued.introducing C # Programming Chapter 2 71
New Employeequeuemonitor (employees);
Monitor.start ();
Monitor.stop ();
Display the Employee list on screen
Console.WriteLine (
"List of employees added via delegate:");
foreach (employee employee in employees)
{
String name = employee. FirstName + "" +
Employee. MiddleName + "" + employee. LastName;
String ssn = employee. SSN;
Console.WriteLine ("Name: {0}, ssn: {1}", Name, SSN);
}
}
catch (Exception Exception)
{
Display any errors on screen
Console.WriteLine (Exception. message);
}
}
}
<summary>
Simulates our message queue.
</summary>
Class Employeequeuemonitor
{
Delegate Signature
Http://www.syngress.com
Figure 2.7 continued
continued.72 Chapter 2 Introducing C # programming
public delegate void Addeventcallback (String FirstName,
String LastName, String middlename, string SSN);
Instance of the delegate
Private Addeventcallback M_addeventcallback;
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;
Create an instace of the delegate and register the
AddEmployee method of the This class as a callback.
M_addeventcallback = new Addeventcallback (
This.addemployee);
}
Drain the queue.
public void Start ()
{
if (m_employees = null)
Return
Http://www.syngress.com
Figure 2.7 continued
Continued.introducing C # programming Chapter 2 73
for (int i = 0; i < m_lengthqueue; i++)
{
String FirstName = m_msgqueue[i,0];
String middlename = m_msgqueue[i,1];
String LastName = m_msgqueue[i,2];
String SSN = m_msgqueue[i,3];
Invoke the callback registered with the delegate
Console.WriteLine ("Invoking Delegate");
M_addeventcallback (FirstName, LastName, MiddleName,
SSN);
}
}
public void Stop ()
{
In a real communications program your would shut down
Gracefully.
}
Called by the delegate when a message to add an employee
is read from the message queue.
public void AddEmployee (string FirstName, String middlename,
String LastName, String SSN)
{
Console.WriteLine ("In delegate, adding employee\r\n");
int index = m_employees. Length;
M_employees[index] = new Employee (FirstName, MiddleName,
LastName, SSN);
}
}
Http://www.syngress.com
Figure 2.7 continued.74 Chapter 2 introducing C # programming
Single Cast
The source code in the previous section is a example to a single cast delegate. A
Single cast delegate invokes only one callback method. Let ' s examine our previous
Sample to the This.
The Employeequeuemonitor class simulates a message queue. It contains a static
Array that holds the current messages. At the top of Employeequeuemonitor are the
Following lines:
public delegate void Addeventcallback (String FirstName,
String LastName, String middlename, string SSN);
Private Addeventcallback M_addeventcallback;
The statement defines a delegate and the parameters an object instance
of the delegate takes. In the case, we are callback to a method of that takes name,
Last name, middle name, and SSN. We'll whenever a request to add a new
Employee appears in the message queue.
The second statement declares a member variable to hold our delegate. It is
Initially set to null. A New object instance must is created prior to making
Method calls through the delegate. An object instance was instantiated in the Con-structor
of Employeequeuemonitor.
M_addeventcallback = new Addeventcallback (this.addemployee);
This statement creates a new object instance of the delegate. The delegate
Takes as an argument the "the" and "call" the delegate is invoked. In this
case, whenever the "delegate is invoked", "method" that would execute is
Employeequeuemonitor.addemployee.
In the "Start method of" Employeequeuemonitor is the following code:
for (int i = 0; i < m_lengthqueue; i++)
{
String FirstName = m_msgqueue[i,0];
String middlename = m_msgqueue[i,1];
String LastName = m_msgqueue[i,2];
String SSN = m_msgqueue[i,3];
Invoke the callback registered with the delegate
Console.WriteLine ("Invoking Delegate");
Http://www.syngress.com.Introducing C # programming Chapter 2 75
M_addeventcallback (FirstName, LastName, MiddleName, SSN);
}
This code simulates draining the ' message queue ' of any waiting messages. The
callback function is invoked by treating the M_addeventcallback member variable
As if it were a to call passing it our four parameters. Note ' You don't
Specify the callback itself when making the call. The delegate maintains the
Address of the callback internally and therefore knows. The
Following example shows what does not:
Incorrect
M_addeventcallback.addemployee (FirstName, LastName, MiddleName, SSN);
Multicast
The true power of delegates becomes apparent when discussing multicast dele-gates.
Let ' s extend our previous example a bit further. Because background pro-cesses
Don't usually have a user interface for human interaction, they typically
Log incoming events for later review. Let ' s add a second callback to We sample to
Log incoming add employee requests. The relevant snippets of the code are shown in
Figure 2.8.The Full Source code was for this sample is on the CD in the file
Multicasting.cs.
Figure 2.8 Relevant portions of the Multicasting.cs program Listing
Class Employeequeuemonitor
{
Delegate Signature for Add employee event callback
public delegate void Addeventcallback (String FirstName,
String LastName, String middlename, string SSN);
Instance of the delegate
Private Addeventcallback M_addeventcallback;
Private Employeequeuelogger M_logger;
Public Employeequeuemonitor (Employees Employees)
{
Http://www.syngress.com
continued.76 Chapter 2 Introducing C # programming
M_employees = employees;
M_lengthqueue = 4;
M_logger = new Employeequeuelogger ("Log.txt");
Register the methods that the delegate'll invoke when a
Add employee message was read from the message queue
M_addeventcallback =
New Addeventcallback (This.addemployee);
M_addeventcallback =
New Addeventcallback (m_logger.logaddrequest);
}
Drain the queue.
public void Start ()
{
if (m_employees = null)
Return
for (int i = 0; i < m_lengthqueue; i++)
{
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");
Invoke the delegate passing the data associated with
Adding a new employee resulting in the subscribed
Callbacks methods being executed, namely
Employees.this.addEmployee ()
Http://www.syngress.com
Figure 2.8 continued
Continued.introducing C # programming Chapter 2 77
and Employeequeuelogger.logaddrequest ()
M_addeventcallback (FirstName, LastName, MiddleName,
SSN);
}
}
Called by delegate whenever a new add employee message
Appears in the message queue. Notice the signature matches
That requried by Addeventcallback
public void AddEmployee (string FirstName, String middlename,
String LastName, String SSN)
{
Console.WriteLine ("In delegate, adding employee\r\n");
int index = m_employees. Length;
M_employees[index] = new Employee (FirstName, MiddleName,
LastName, 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 delegate whenever a new add employee message
Http://www.syngress.com


Related Article

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.