Example #1
0
        //---------------------------------------------------------------------
        /// <summary>
        /// Notify, send a message.
        /// Execute all actions susbscribed under the msgCode.
        ///
        /// Return the number of actions notifications executed, or -1 if an error occurs.
        /// If no subscriber is found return 0.
        /// </summary>
        /// <param name="messengerName"></param>
        /// <param name="obj"></param>
        public int Notify <T>(object whoNotify, string msgCode, T obj)
        {
            _lastErrCode = MessengerErrCode.None;

            // check params
            if (whoNotify == null)
            {
                _lastErrCode = MessengerErrCode.ObjNotifyIsNull;
                return(-1);
            }

            // the syntax code must be ok
            if (!IsMsgCodeSyntaxOk(msgCode))
            {
                _lastErrCode = MessengerErrCode.MsgCodeSyntaxWrong;
                return(-1);
            }

            // find the CodeListAction
            if (!_dictMsgCodeListAction.ContainsKey(msgCode))
            {
                _lastErrCode = MessengerErrCode.MsgCodeNotFound;
                // not an error
                return(0);
            }

            // msg code already exists, get it
            MsgCodeListAction msgCodeListAction = _dictMsgCodeListAction[msgCode];

            // execute all actions presents
            int notifCount = 0;
            List <RecipientObjAction> listRemoveRecipientAction = new List <RecipientObjAction>();

            foreach (RecipientObjAction recipientAction in msgCodeListAction.GetListRecipientObjAction())
            {
                // check that the object already exists (with the weak reference)
                if (recipientAction.Recipient != null)
                {
                    // the type of the notify parameter should match the type of the param of the registered recipient
                    if (recipientAction.ActionType == typeof(T))
                    {
                        // ok, execute the action
                        ((Action <T>)recipientAction.ActionT)(obj);
                        notifCount++;
                    }
                }
                else
                {
                    // the recipient is now null, unregister it
                    listRemoveRecipientAction.Add(recipientAction);
                }
            }

            //now remove all unregistered recipient
            while (listRemoveRecipientAction.Count > 0)
            {
                msgCodeListAction.RemoveRecipientObjAction(listRemoveRecipientAction[0]);
                listRemoveRecipientAction.RemoveAt(0);
            }

            // no recipient-action attached to the msgCode, remove the msgCode
            if (msgCodeListAction.Count == 0)
            {
                RemoveMsgCodeListAction(msgCodeListAction);
            }

            return(notifCount);
        }