首页 > 开发 > 综合 > 正文

Using Delegates and Events 1 (来自一本49美元/817页2002年的书

2024-07-21 02:17:19
字体:
来源:转载
供稿:网友

using delegates and events
if you are familiar with windows programming, you’ve most likely dealt with
callbacks. callbacks are method calls that are executed when some event happens
http://www.syngress.com.70 chapter 2 • introducing c# programming
during processing. for instance, a callback can be established to handle the pro-cessing
of an incoming message on a communications port. another part of the
communications program can wait for 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/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 when an event occurs. this is termed multicasting.
delegates
let’s extend our 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 will be a static array, but in the real world it could be 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 point for 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 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 you 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 an example of a single cast delegate. a
single cast delegate invokes only one callback method. let’s examine our previous
sample to see 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 first statement defines a delegate and the parameters an object instance
of the delegate takes. in this case, we callback to a method that takes first name,
last name, middle name, and ssn. we do this 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 be created prior to making
method calls through the delegate. an object instance is 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 method to call when the delegate is invoked. in this
case, whenever the delegate is invoked, the method that will 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 method call passing it our four parameters. note that you do not
specify the callback itself when making the call.the delegate maintains the
address of the callback internally and therefore knows the method to call.the
following example shows what not to do:
// 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
do not usually have a user interface for human interaction, they typically
log incoming events for later review. let’s add a second callback to our sample to
log incoming add employee requests.the relevant snippets of code are shown in
figure 2.8.the full source code is 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 will invoke when an
// add employee message is 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
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表