Добавил:
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

41

 

 

 

! Compile and test the program

Build the program and run it.

The guidelines-based event chat output should resemble the following:

...

Demo start: Guidelines Based Event Chat Server. Server: GChatServer

Msg arrived (Client 1): Hi to all clients Server: GChatServer

Msg arrived (Client 2): Hi to all clients Server: GChatServer

Msg arrived (Client 3): Hi to all clients Server: GChatServer

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

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

Demo stop: Guidelines Based Event Chat Server.

42

Module 8: Delegates and Events

Review

Topic Objective

To reinforce module objectives by reviewing key points.

Lead-in

The review questions cover some of the key concepts taught in this module.

!Delegates

!Multicast Delegates

!Events

!When to Use Delegates, Events, and Interfaces

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

1.Write the code to declare a delegate that is named ProcessOrderCallback for the following method:

static public bool ProcessOrder(int Quantity, string Item) { //...

}

public delegate bool ProcessOrderCallback (int Quantity, string, string Item);

2.Write the code to call the following EnterOrder method, instantiating and passing an instance of the ProcessOrderCallback delegate that refers to a public static method that is named Foo in the public class Bar.

static public void EnterOrder(

ProcessOrderCallback processOrderCallback) { //...

};

EnterOrder( new ProcessOrderCallback(Bar.Foo) );

Module 8: Delegates and Events

43

 

 

 

3.Write the body of the static method EnterOrder that takes as an argument an instance of the delegate that is declared in question 1. EnterOrder outputs to the console strings to prompt for an item name and quantity and reads in the user’s input. EnterOrder should invoke the callback delegate with this information.

static public void EnterOrder( ProcessOrderCallback processOrderCallback) { Console.WriteLine("Enter Item Name:");

string name = Console.ReadLine(); Console.WriteLine("Enter Item Quanity:");

int quantity = Int32.Parse( Console.ReadLine() ); processOrderCallback(quantity, name);

}

4.Using the following declarations, write the code to add delegate b to a’s invocation list.

delegate void MyDelegate(); MyDelegate a, b;

a = new MyDelegate(Bar1.Foo1); b = new MyDelegate(Bar2.Foo2); a += b;

5.Use the event keyword to write the code to declare a public static event for a delegate type ProcessOrderEventHandler.

public static event ProcessOrderEventHandler processOrderHandler;

6.Describe when you should use a delegate and when you should use an event.

Use a delegate when:

You want a C-style function pointer.

You want single callback invocation.

You want the callback function to be registered in the call or at construction time, not in a separate add method.

Use an event when:

Client code signs up for the callback prior to the occurrence of events, typically through a separate add method.

More than one client object will be affected.

Module 9: Memory and

Resource Management

Contents

 

Overview

1

Memory Management Basics

2

Non-Memory Resource Management

12

Implicit Resource Management

13

Explicit Resource Management

26

Optimizing Garbage Collection

36

Lab 9: Memory and Resource Management 48

Review

55

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

2001-2002 Microsoft Corporation. All rights reserved.

Microsoft, ActiveX, BizTalk, IntelliMirror, Jscript, MSDN, MS-DOS, MSN, PowerPoint, Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows Media, and

Window NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Module 9: Memory and Resource Management

iii

 

 

 

Instructor Notes

Presentation:

125 Minutes

Lab:

60 Minutes

After completing this module, students will be able to:

!Describe how garbage collection manages object memory.

!Implicitly manage non-memory resources by using a destructor’s finalize code.

!Explicitly manage non-memory resources by using client-controlled deterministic release of resources.

!Write code by using the temporary resource usage design pattern.

!Programmatically control the behavior of the garbage collection.

!Describe advanced garbage collection features.

Materials and Preparation

This section provides the materials and preparation tasks that you need to teach this module.

Required Materials

To teach this module, you need the Microsoft® PowerPoint® file 2349B_09.ppt.

Preparation Tasks

To prepare for this module, you should:

!Read all of the materials for this module.

!Review the animation.

!Practice the demonstrations.

!Complete the lab.

iv

Module 9: Memory and Resource Management

Demonstrations

This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes.

The code for each of the following demonstrations is contained in one project and is located in <install folder>\Democode\Mod09\

GARBAGE COLLECTION. In addition, the code for the individual demonstrations is provided in the student notes.

Use the debugger to step through the code while you point out features and ask students what they think will happen next.

Finalization

In this demonstration, you will show students how garbage collection handles finalization and resurrection. In this demonstration, run the Introduction and

ResurrectionDemo methods.

The IDisposable Interface

In this demonstration, you will show students how to perform explicit resource management by using the IDisposable interface. In this demonstration, run the

DisposeDemo method.

Weak References

In this demonstration, you will show students how garbage collection handles weak references. In this demonstration, run the WeakRefDemo method.

Generations

In this demonstration, you will show students how garbage collection handles generations. In this demonstration, run the GenerationDemo method.

Multimedia

This section lists the multimedia items that are part of this module. Instructions for launching and playing the multimedia are included with the relevant slides.

Simple Garbage Collection

This animation will show students the Microsoft .NET Framework common language runtime’s garbage collection process without finalization.

Garbage Collection

This animation will show students the .NET Framework common language runtime garbage collection process, including finalization.

Module 9: Memory and Resource Management

v

 

 

 

Module Strategy

Use the following strategy to present this module:

! Memory Management Basics

!

!

Students in your classes will probably use different approaches to memory management. Begin with a brief review of different memory management techniques that you or the students may have learned from experience.

Because students will need to adapt their programming practices to the automatic memory management that is provided by the common language runtime, it is important to mention other memory management techniques.

Compare and contrast manual memory management with the automatic memory management that is provided by the common language runtime. Outline the simple garbage collection process without the finalization details and use the Simple Garbage Collection animation to help the students understand the concept of the garbage collection process more easily.

Instructions for running the animations in this module are included in Instructor Margin Notes.

Non-Memory Resource Management

This topic is an introduction to handling non-memory resources implicitly and explicitly. Tell students that the next two sections cover these areas in detail. You should not spend much time on this slide.

Implicit Resource Management

Introduce the finalization phase of the garbage collection process. Emphasize that in C#, a destructor must be used for the finalization code. The second animation, Garbage Collection, is more complex than the first. It shows the garbage collection process with the finalization details.

Spend time discussing the drawbacks that are associated with finalization and what to do if finalization is required. Show students how to deal with an object that has been resurrected.

Use the Finalization demonstration to highlight how garbage collection deals with finalization and resurrection.

!Explicit Resource Management

Show students how to perform explicit resource management by using the IDisposable interface and Dispose method.

Discuss the temporary resource usage design pattern as an example of how to allocate resources for temporary use.

!Optimizing Garbage Collection

Use the demonstrations that are provided to show how to optimize garbage collection through weak references and generations.

In addition to discussing the programmatic optimizations that can be made to the garbage collection process, briefly mention the use of performance counters to monitor memory activity and the use of a multiprocessor system to scale applications where there are garbage collection bottlenecks.

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