CommandAsyncExecutor

CommandAsyncExecutor<TCommand> executes commands asynchronously using ThreadPool. In the opposite to the ThreadPool it notifies when the command is completed. CommandAsyncExecutor is a lightweight object and creating an instance of CommandAsyncExecutor for each command type is a common practice.

    public class CommandAsyncExecutor<TCommand> where TCommand : IMcmCommand
    {
        public void ExecuteAsync(TCommand command) {...}
        public event CommandEventHandler<TCommand> ExecuteCompleted;
    }
CommandEventHandler contains reference to the executed command.
CommandAsyncExecutor is created and used internally by Component.

Usage

private CommandAsyncExecutor<LoginCommand> _loginCommandAsyncExecutor;

[MessageSubscriber("MyMessages"]
private void handleLoginRequestMessage(LoginRequestMessage m)
{
    _loginCommandAsyncExecutor = new CommandAsyncExecutor<LoginCommand>();
    _loginCommandAsyncExecutor.ExecuteCompleted += on_loginCommandAsyncExecutor_ExecuteCompleted;

    var arg = new LoginCommandArgument(m.Name, Env.Components.TimeProvider);
    var cmd = new LoginCommand(arg);

    _loginCommandAsyncExecutor.ExecuteAsync(cmd);
}

private void on_loginCommandAsyncExecutor_ExecuteCompleted(object sender, CommandEventArgs<LoginCommand> e)
{
    var mes = new LoginResponseMessage(e.Command.Error);
    if (!mes.HasError)
    {
        // no error
        mes.Greeting = e.Command.Result.Greeting;
    }

    Env.MainMessageChannel.Post(mes);
}

Last edited Jan 24, 2013 at 10:05 PM by polo, version 4

Comments

No comments yet.