Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
194
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 8: Delegates and Events

31

 

 

 

When to Use Delegates, Events, and Interfaces

Topic Objective

To explain when to use delegates, events, and interfaces.

Lead-in

Delegates, interfaces, and events all provide callback functionality, but each has specific usage characteristics that make it better suited to particular situations.

!Use a Delegate If:

#You basically want a C-style function pointer

#You want single callback invocation

#The callback should be registered in the call or at construction time, not through an add method call

!Use Events If:

#Client signs up for the callback function through an add method call

#More than one object will care

#You want end users to be able to easily add a listener to the notification in the visual designer

!Use an Interface If:

#The callback function entails complex behavior, such as multiple methods

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Delegates, interfaces, and events all provide callback functionality, but each has specific usage characteristics that make it better suited to particular situations.

Use a delegate if:

!You basically want a C-style function pointer.

!You want single callback invocation.

!You want the callback function registered in the call or at construction time, not through an add method call.

Use events if:

!Client code signs up for the callback prior to the occurrence of events, typically through an add method call.

!More than one client object will care.

!You want end users to be able to easily add a listener to the notification in the visual designer.

Use an interface if:

The callback function entails complex behavior, as when more than one callback method is invoked.

32

Module 8: Delegates and Events

Lab 8: Creating a Simple Chat Server

Topic Objective

To introduce the lab.

Lead-in

In this lab, you will create use delegates and events with a simple chat server application.

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Objectives

After completing this lab, you will be able to:

!Write code that uses the delegate class to create type-safe callbacks.

!Write code that uses the event keyword to simplify and improve the implementation of a class that raises events.

!Write event code that conforms to the .NET Framework guidelines.

Lab Setup

Only solution files are associated with this lab. The solution files for this lab are in the folder <install folder>\Labs\Lab08\Solution.

Scenario

In this lab, you will create a simple chat-style server to which multiple clients can connect. When one client sends a string message to the server, the server forwards the message to all registered clients that have not been specifically excluded.

You should note that a real chat application would be based on a more scalable and flexible design to connect client and servers, such as a publish-and- subscribe design.

Estimated time to complete this lab: 60 minutes

Module 8: Delegates and Events

33

 

 

 

Exercise 1

Creating a Simple Chat Server Using Delegates

In this exercise, you will implement a simple chat server and clients by using delegates.

Scenario

Each client will register a delegate with the server. Then, when a client sends a message to the server, the server forwards the message to all specified clients. This implementation uses delegates as a callback mechanism.

! Create a Visual Studio .NET project

Open Visual Studio .NET and create a new C# Console Application project named chat1 in <install folder>\Labs\Lab08.

! Create the chat server class

1.Create the chat server class and name it DChatServer.

2.Declare within the DChatServer class a delegate that will be used to invoke the callback function in the client when a chat message arrives.

a.Name the delegate OnMsgArrived.

b.Declare this delegate public and reflect the callback function’s signature. The callback’s signature is a void return value with a single argument of type string.

3.Define a field to store the connected clients’ delegates by performing the following steps.

a.Name the field onMsgArrived.

b.Make the field a private static reference to the type of the delegate,

OnMsgArrived.

4.Define the method that will be called by a client to connect that client to the server by performing the following steps.

a.Name the method ClientConnect.

b.Declare the method public static void.

c.Include an argument of type OnMsgArrived.

d.Create the method’s implementation by using the delegate’s Combine method to add this new delegate to the delegate stored in the onMsgArrived invocation list.

As an alternative to the Combine method, you can use the += operator.

5.Define a method that will be called by a client to disconnect that client from the server by performing the following steps.

a.Name the method ClientDisconnect.

b.Declare the method public static void.

c.Declare the method so that it has the same signature as ClientConnect.

d.Create the method’s implementation by using the delegate’s Remove method to remove the delegate from the onMsgArrived invocation list.

As an alternative to the Remove method, you can use the -= operator.

34Module 8: Delegates and Events

6.Define a method that will send a specified message to the connected clients, with the possible exception of one client, by performing the following steps.

a.Name the method SendMsg.

b.Declare the method public static void.

c.Declare the method so that it takes two arguments: a string argument for the message and an object argument for the excluded client.

d.Create the method’s implementation.

i.If the excluded client argument is null, invoke the multicast delegate to send the message to all the clients.

ii.If the excluded client argument is not null, iterate through the onMsgArrived delegate’s invocation list and invoke only those delegates that do not match the excluded client argument.

!Create the chat client class

1.Create the chat client class and name it DChatClient.

2.Implement within the DChatClient class a callback method that the server will invoke by a delegate when the server receives a chat message.

a.Name the method onMsgArrived.

b.Declare the method private void.

c.Declare the method so that it takes a single string argument.

d.Create the method’s implementation so that it prints the name of the client along with the string argument to the console.

3.Add a constructor that will receive the name of the client as a parameter and connect the client with the server.

a.Declare the constructor so that it takes a string argument that represents the client’s name.

b.Create the constructor’s implementation.

i.Store the client’s name in a private field.

ii.Connect the client to the server by calling the server’s

ClientConnect method.

The call’s argument should be an instance of the delegate type DChatServer.OnMsgArrived that was instantiated with the client’s callback method: onMsgArrived.

Module 8: Delegates and Events

35

 

 

 

! Create the program’s main entry point

1.Name the class that contains the program’s standard Main entry point,

Application.

Typically, a Visual Studio .NET project creates the class with the Main entry point for you. You may only need to rename this class.

2.Write to the console a line of text to indicate that the program is starting.

3.Instantiate three DChatClient objects, passing the client names “1”, “2”, and “3” to the constructor.

4.Send a message to the server by invoking the static method SendMsg of the DChatServer. The message should be sent to all clients.

5.Send a second message to all clients, except Client 2.

6.Write to the console a line of text to indicate that the program is finished.

! Compile and test the program

Build the program and run it.

The output should resemble the following:

Demo start: Delegate Chat Server.

Msg arrived (Client 1): Hi to all clients

Msg arrived (Client 2): Hi to all clients

Msg arrived (Client 3): Hi to all clients

Msg arrived (Client 1): Hi to all clients except client 2

Msg arrived (Client 3): Hi to all clients except client 2

Demo stop: Delegate Chat Server.

36

Module 8: Delegates and Events

Exercise 2

Creating a Simple Chat Server Using Events

In this exercise, you will implement a simple chat server and clients by using events and delegates. This implementation uses the event keyword, which hides some of the low-level code details associated with delegates and prevents clients from accessing or invoking the delegates of other clients.

Scenario

Each client will connect with the server’s “on message arrived” event. Then, when one client sends a string message to the server, the server forwards the message to all specified connected clients.

!Access the chat1 Visual Studio .NET project

Open Visual Studio .NET and open the project named chat1, which you created in Exercise 1, in <install folder>\Labs\Lab08. Open the previously created C# source file and perform the following procedures.

!Create the event-based chat server class

1.Create a new chat server class and name it EChatServer.

2.Declare within the EChatServer class a delegate that will be used to invoke the callback function in the client when a chat message arrives.

a.Name the delegate OnMsgArrived.

b.This delegate should be declared public and reflect the callback function’s signature.

The callback’s signature is a void return value with a single argument of type string.

3.Declare an event for the OnMsgArrived delegate type.

a.Name the event onMsgArrived.

b.Declare the event public static.

4.Define a method that will send a specified message to the connected clients, with the possible exception of one client.

a.Name the method SendMsg.

b.Declare the method public static void.

c.Declare the method so that it takes two arguments: a string argument for the message and an object argument for the excluded client.

d.Create the method’s implementation.

i.If the excluded client argument is null, invoke the multicast delegate to send the message to all of the clients.

ii.If the excluded client argument is not null, iterate through the onMsgArrived delegate’s invocation list and invoke only those delegates that do not match the excluded client argument.

Module 8: Delegates and Events

37

 

 

 

! Create the event-based chat client class

1.Create a new chat client class and name it EChatClient.

2.Implement within the EChatClient class a callback method that the server will invoke by a delegate when the server receives a chat message.

a.Name the method onMsgArrived.

b.Declare the method private void.

c.Declare the method so that it takes a single string argument.

d.Implement the method so that it prints the name of the client, together with the string argument, to the console.

3.Add a constructor that will receive the name of the client as a parameter and connect the client with the server.

a.Declare the constructor so that it takes a string argument that represents the client’s name.

b.Create the constructor’s implementation.

i.Store the client’s name in a private field.

ii.Connect the client to the server by using the += operator to add a new delegate instance to the EChatServer’s event.

The += operator’s right operand should be an instance of the delegate type EChatServer.OnMsgArrived that was instantiated with the client’s callback method, onMsgArrived.

!Extend the program’s main entry point by performing the following procedures

1.Write to the console a line of text to indicate that the event chat portion of the program is starting.

2.Instantiate three EChatClient objects, passing the client names “1”, “2”, and “3” to the constructor.

3.Send a message to the server by invoking the static method SendMsg of the EchatServer. You should send the message to all clients.

4.Send a second message to all clients except client 2.

5.Write to the console a line of text to indicate that event chat is finished.

! Compile and test the program

Build the program and run it.

The output should resemble the following:

...

Demo start: Event Chat Server.

Msg arrived (Client 1): Hi to all clients

Msg arrived (Client 2): Hi to all clients

Msg arrived (Client 3): Hi to all clients

Msg arrived (Client 1): Hi to all clients except client 2

Msg arrived (Client 3): Hi to all clients except client 2

Demo stop: Event Chat Server.

38

Module 8: Delegates and Events

Exercise 3 (As Time Permits)

Conforming to the .NET Framework Guidelines

In this exercise, you will implement the simple chat program with events that conform to the .NET Framework guidelines. Although the C# language allows events to use any delegate type, the .NET Framework has stricter guidelines on the delegate types that should be used for events. If you intend for your component to be used with the .NET Framework, follow these guidelines.

Scenario

As in Exercise 2, each client connects with the server’s event. Then, when one client sends a string message to the server, the server forwards the message to all specified clients.

In this exercise, the delegate type will conform to the .NET Framework guidelines. The delegate type will take two parameters, an object source parameter, which indicates the source of the event, and an e parameter, which encapsulates information about the event and, in this case, includes the string message that generated the event.

In this exercise, you will also instantiate the chat server as an object. Instantiating the chat server will allow you to invoke the connected client’s delegates with a non-null object source parameter.

!Create the event class that will encapsulate the event’s state

1.Open Visual Studio .NET and open the project named chat1, which you created in Exercise 1, in location <install folder>\Labs\Lab08. Open the previously created C# source file and add the following code.

2.Create a new public class named MsgArrivedEventArgs that inherits from

EventArgs.

3.Declare within MsgArrivedEventArgs a private readonly field of type string named message.

4.Declare a public constructor that takes a single string argument and stores it in the field named message.

5.Add a property named Message that returns the value of message.

Module 8: Delegates and Events

39

 

 

 

! Create the guidelines-based chat server class

1.Create a new chat server class and name it GChatServer.

2.Declare within the GChatServer class a delegate that will be used to invoke the function in the client when a chat message arrives.

a.Name the delegate MsgArrivedEventHandler.

b.This delegate should be declared public and reflect the guideline’s signature of a void return value and two arguments of type object and

MsgArrivedEventArgs.

3.Declare an event for the MsgArrivedEventHandler delegate type.

a.Name the event MsgArrivedHandler.

b.Make the event public. Do not make it static.

4.Define a method that will send a specified message to the connected clients, with the possible exception of one client.

a.Name the method SendMsg.

b.Declare the method public void.

c.Declare the method so that it takes two arguments: a string argument for the message and an object argument for the excluded client.

d.Create the method’s implementation.

i.Instantiate an instance of the event class MsgArrivedEventArgs with the message string.

ii.Invoke the OnMsgArrived method, which is implemented in the next step.

5.Define the OnEvent method to raise the event.

a.Name the method OnMsgArrived. In accordance with the .NET Framework guidelines declare the method protected virtual void with two arguments of type MsgArrivedEventArgs and object.

b.Create the method’s implementation.

i.If the event’s field contains a non-null delegate list and the excluded client argument is null, invoke the multicast delegate with the appropriate arguments.

ii.If the event’s field contains a non-null delegate list and the excluded client argument is not null, iterate through the MsgArrivedHandler delegate’s invocation list and invoke only those delegates that do not match the excluded client argument.

iii.If the event’s field contains a null delegate list, do nothing.

40Module 8: Delegates and Events

!Create the guidelines-based chat client class

1.Create a new chat client class and name it GChatClient.

2.Implement within the GChatClient class a callback method that the server will invoke by a delegate when the server receives a chat message.

a.Name the method onMsgArrived.

b.Declare the method private void.

c.Declare the method so that it takes an object and

MsgArrivedEventArgs arguments.

d.Create the method’s implementation so that it prints the name of the client, the Message property of MsgArrivedEventArgs, and the server object as a string to the console.

3.Add a constructor that will receive the name of the client and a reference to the server, and will connect the client with the server.

a.Declare the constructor so that it takes a string argument that represents the client’s name and a GChatServer argument that specifies the server object.

b.Create the constructor’s implementation.

i.Store the client’s name in a private field.

ii.Store the server’s reference in a private field.

iii.Connect the client to the server by using the += operator to add a new delegate instance to the GChatServer’s event.

The += operator’s right operand should be an instance of the delegate type GChatServer.MsgArrivedEventHandler that was instantiated with the client’s callback method: onMsgArrived.

!Extend the program’s main entry point by performing the following procedures

1.Create an instance of the GChatServer object.

2.Write to the console a line of text to indicate that the guidelines-based chat server class portion of the program is starting.

3.Instantiate three GChatClient objects, passing the client names “1”, “2”, and “3” to the constructor.

4.Send a message to the server by invoking the SendMsg method of GChatServer. The message should be sent to all clients.

5.Send a second message to all clients except client 2.

6.Write to the console a line of text to indicate that the guidelines-based event chat is finished.

Соседние файлы в папке c#