Type that defines lots of events

  1. Why do we need to implement a special version of type that defines lots of events?
  2. How to avoid memory overhead using the EventHandlerList class?

Standard implementation of a type with lots of events would cause memory overhead because it would require creating equal number of delegates.

To avoid memory overhead we can use the EventHandlerList class and to control adding and removing methods to events.

Example 1:

 

    public class TypeWithLotsOfEventsEventArgs : EventArgs

    {

        public string Data { set; get; }

    }

 

    public class TypeWithLotsOfEvents

    {

        private static readonly Object _firstEvent = new Object();

        private static readonly Object _secondEvent = new Object();

 

        private EventHandlerList _events;

 

        private EventHandlerList Events

        {

            get

            {

                if (_events == null)

                {

                    _events = new EventHandlerList();

                }

                return _events;

            }

        }

 

        public event EventHandler<TypeWithLotsOfEventsEventArgs> FirstEvent

        {

            add { Events.AddHandler(_firstEvent, value); }

            remove { Events.RemoveHandler(_firstEvent, value); }

        }

 

        public event EventHandler<TypeWithLotsOfEventsEventArgs> SecondEvent

        {

            add { Events.AddHandler(_secondEvent, value); }

            remove { Events.RemoveHandler(_secondEvent, value); }

        }

 

        public void FirstMethod(string data)

        {

            EventHandler<TypeWithLotsOfEventsEventArgs> firstEvent = (EventHandler < TypeWithLotsOfEventsEventArgs>) Events[_firstEvent];

 

            TypeWithLotsOfEventsEventArgs args = new TypeWithLotsOfEventsEventArgs();

            args.Data = data;

 

            if (firstEvent != null)

                firstEvent(this, args);

        }

 

        public void SecondMethod(string data)

        {

            EventHandler<TypeWithLotsOfEventsEventArgs> secondEvent = (EventHandler<TypeWithLotsOfEventsEventArgs>)Events[_secondEvent];

 

            TypeWithLotsOfEventsEventArgs args = new TypeWithLotsOfEventsEventArgs();

            args.Data = data;

 

            if (secondEvent != null)

                secondEvent(this, args);

        }

    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s