Event Accessors Sample 

Visual Studio 2005

Download sample

This sample shows how to create and use event accessors. This feature allows you to customize the implementation of an event and write custom AddHandler, RemoveHandler, and RaiseEvent support. This is often used to optimize memory used by server controls and make them more robust in the face of badly behaved callers and handlers.

Security noteSecurity Note

This sample code is provided to illustrate a concept and should not be used in applications or Web sites, as it may not illustrate the safest coding practices. Microsoft assumes no liability for incidental or consequential damages should the sample code be used for purposes other than as intended.

To open the sample file in Solution Explorer

  1. Click Download Sample.

    The File Download message box appears.

  2. Click Open, and on the left column of the zip folder window, click Extract all files.

    The Extraction Wizard opens.

  3. Click Next. You can change the directory that the files will be extracted to, and then click Next again.

  4. Make sure that the Show extracted files check box is selected, and click Finish.

  5. Double-click the sample's .sln file.

    The sample solution is displayed in Solution Explorer. You might get a security warning that says the solution location is not trusted. Click OK to continue.

To run this sample

  • Press F5.

Demonstrates

This sample creates two controls, MemoryOptimizedBaseControl and ReliabilityOptimizedControl. Each raises a Click event every five seconds. The difference between the two classes is in how the events are implemented.

Memory-efficient custom control   The MemoryOptimizedBaseControl control uses event accessors to optimize the memory consumed by creating events on the server control. The internal EventList object will only be used if the calling code adds an event handler for the Click event. An internal timer is used to simulate server events being fired.

Reliable custom control   The ReliabilityOptimizedControl uses event accessors to create a more reliable server control. The server control always fires the Click event asynchronously using BeginInvoke, and this ensures that event handlers on the client do not block one another. This means that a badly behaved event handler will not block others from being handled. An internal timer is used to simulate server events being fired.

See Also

Community Additions

ADD
Show: