Exemple #1
0
        /// <summary>
        /// Listens for a message with the given type and predicate once and then stops listening
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="broker"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        public static ListenerToken ListenOnce <T>(this IMessageBroker broker, Predicate <T> predicate, Action <T> handler) where T : Message
        {
            if (handler == null)
            {
                throw new ArgumentNullException("handler");
            }

            ListenerToken token = null;

            Action <T> handlerWrapped = new Action <T>(t =>
            {
                // Stop listening first then pass to the handler
                if (t.Exception != null)
                {
                    token.StopListening(t.Exception);
                    return;
                }

                token.StopListening();
                handler(t);
            });

            token = broker.Listen <T>(predicate, handlerWrapped);

            return(token);
        }
        //////////////////////////////////////////////////////////////////////

        #region Public Methods

        /// <summary>
        /// Awaits a response to the message associated with the MessageToken
        /// </summary>
        /// <returns>A Task object which can be awaited on until a response is received to the Message</returns>
        public async Task AwaitResponse()
        {
            ListenerToken token = null;

            token = broker.ListenOnce <Message>(m => m.ReferenceId == message.Id);

            await token.Completion;
        }
        /// <summary>
        /// Awaits a response to the message associated with the MessageToken with a given response message
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <returns>A Task object which can be awaited on until a response is received to the Message</returns>
        public async Task <T> AwaitResponse <T>() where T : Message
        {
            ListenerToken token = null;

            T result = default(T);

            token = broker.ListenOnce <T>(m => m.ReferenceId == message.Id, m =>
            {
                result = m;
            });

            await token.Completion;

            return(result);
        }