Exemplo n.º 1
0
        /// <summary>
        /// Adds a weak subscription to the specified handler.
        /// </summary>
        /// <param name="source">
        /// The object that is the source of the event.
        /// </param>
        /// <param name="eventName">
        /// The name of the event.
        /// </param>
        /// <param name="handler">
        /// The handler to subscribe.
        /// </param>
        static public void Subscribe <THandler>(object source, string eventName, THandler handler) where THandler : class
        {
            // Verify delegate type
            VerifyDelegate <THandler>();

            // Try to find existing
            var reg = FindRegistration(source, eventName);

            // If not found, create one and store it
            if (reg == null)
            {
                reg = new WeakEvent(source, eventName);
                registrations.Add(reg);
                #if WEAK_LOGGING
                Debug.WriteLine(string.Format("Creating new registration for event '{0}' and object ID {1}. Total registrations: {2}", eventName, source.GetHashCode(), registrations.Count));
                #endif
            }
            #if WEAK_LOGGING
            else
            {
                Debug.WriteLine(string.Format("Reusing existing registration for event '{0}' and object ID {1}. Total registrations: {2}", eventName, source.GetHashCode(), registrations.Count));
            }
            #endif

            // Add the subscription
            reg.Subscribe(handler as Delegate);
        }
Exemplo n.º 2
0
        static private WeakEvent FindRegistration(object source, string eventName)
        {
            // Look for registration
            WeakEvent reg = null;

            for (int iReg = registrations.Count - 1; iReg >= 0; iReg--)
            {
                // Get the registration
                reg = registrations[iReg];

                // If the source is dead, remove the registration
                if ((reg != null) && (!reg.source.IsAlive))
                {
                    registrations.RemoveAt(iReg);
                    #if WEAK_LOGGING
                    Debug.WriteLine(string.Format("Removing registration for event '{0}' due to expired object instance. New total registrations: {1}", eventName, registrations.Count));
                    #endif
                    reg = null;
                }

                // If it's the right source, done searching
                if ((reg.source.Target == source) && (reg.eventName == eventName))
                {
                    break;
                }
                else
                {
                    reg = null;
                }
            }

            // Done searching
            return(reg);
        }