Exemplo n.º 1
0
        /// <summary>
        /// Start hosted command handler.
        /// </summary>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>Completed asynchronous task.</returns>
        public virtual Task Start(CancellationToken cancellationToken = default(CancellationToken))
        {
            // Get an instance provided by child class and store in a private property.
            _internalCommandSource = CommandSource;

            if (_internalCommandSource == null)
            {
                throw new InvalidOperationException("Hosted command handler has no command source.");
            }

            OnStart();

            // Subscribe.
            _internalCommandSource.CommandReceived += (receivedCommand, ct) =>
            {
                TCommand command = receivedCommand as TCommand;
                if (command != null)
                {
                    ProcessCommandAsync(command, cancellationToken);
                }

                return(TaskUtility.CompletedTask);
            };

            _internalCommandSource.StartReceiving(cancellationToken);

            return(TaskUtility.CompletedTask);
        }