Asynchronous Commands with Oakton 1.4

Oakton is a little command line parsing and execution library that I use within Storyteller, Marten, and Jasper. The benefit of Oakton over the other bazillion command line parsing tools in .Net is the way it completely separates command execution from string parsing.

The big downside and most frequent request to Oakton on its initial rollout was that it lacked support for asynchronous commands (it’s a descendent of code I originally wrote into FubuCore back in 2010 when nobody cared about asynchronous code yet). Not to worry thought, because Andy Dote just added support for that shows up in the Oakton 1.4.0 release.

To write an asynchronous command, use the new AsyncOaktonCommand base class like so:

    [Description("Say my name", Name = "say-async-name")]
    public class AsyncSayNameCommand : OaktonAsyncCommand
    {
        public AsyncSayNameCommand()
        {
            Usage("Capture the users name").Arguments(x => x.FirstName, x => x.LastName);
        }

        public override async Task Execute(SayName input)
        {
            await Console.Out.WriteLineAsync($"{input.FirstName} {input.LastName}");

            return true;
        }
    }

To execute commands asynchronously all the way through your Program.Main() function, use the new asynchronous overloads in CommandExecutor like so:

        static Task<int> Main(string[] args)
        {
            var executor = CommandExecutor.For(_ =>
            {
                // Find and apply all command classes discovered
                // in this assembly
                _.RegisterCommands(typeof(Program).GetTypeInfo().Assembly);
            });

            return executor.ExecuteAsync(args);
        }

 

One thought on “Asynchronous Commands with Oakton 1.4

Leave a comment