Ejemplo n.º 1
0
        private static WeakEvent FindRegistration(object source, string eventName)
        {
            // Look for registration
            WeakEvent reg = null;

            for (var 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);
                    reg = null;
                }

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

            // Done searching
            return(reg);
        }
Ejemplo n.º 2
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>
        public static 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);
            }

            // Add the subscription
            reg.Subscribe(handler as Delegate);
        }