Skip to content


The last example from the Piped arguments page

$ dotnet linq.dll Range 1 4 10000 | dotnet linq.dll Sum

will take 40 seconds to execute. The way it's currently configured, the user is stuck waiting until the command completes.

With console applications, the standard pattern is to exit the app when Ctrl+C is pressed. Here's how we support that pattern with CommandDotNet.

public class Program
    static int Main(string[] args) => AppRunner.Run(args);

    public static AppRunner AppRunner => 
        new AppRunner<Program>()

    // could also use .UseDefaultMiddleware()

    public void Range(IConsole console, CancellationToken ct, int start, int count, int sleep = 0)
        foreach (var i in Enumerable.Range(start, count).UntilCancelled(ct, sleep))

    public void Sum(IConsole console, CancellationToken ct, IEnumerable<int> values)
        int total = 0;
        foreach (var value in values.ThrowIfCancelled(ct))
            console.WriteLine(total += value);
snippet source | anchor

Again, CommandDotNet makes this very easy. Configure the app with appRunner.UseCancellationHandlers() which configures a CancellationToken that can be injected into your command and interceptor methods.

Use either of the two handy extension methods UntilCancelled or ThrowIfCancelled to exit an enumeration early when cancellation has been requested.