All Pages All Books|
|
|||||
|
70
|
Chapter 2 • Introducing C# Programming
|
||||
|
|
|||||
|
during processing. For instance, a callback can be established to handle the processing 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
|
|||||
|
|
|||||
|
t
|
Let’s extend our employees sample to use delegates. This sample simulates a background 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 =
Continued
|
|||||
|
|
|||||
|
|
|
||||
|
|
|||||
All Pages All Books