System.CommandLine 内で終了を処理する方法

重要

System.CommandLine は現在プレビュー段階であり、このドキュメントはバージョン 2.0 beta 4 を対象としています。 一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。

終了を処理するには、ハンドラー コードに CancellationToken インスタンスを挿入します。 次の例に示すように、このトークンは、ハンドラー内から呼び出す非同期 API に渡すことができます。

static async Task<int> Main(string[] args)
{
    int returnCode = 0;

    var urlOption = new Option<string>("--url", "A URL.");

    var rootCommand = new RootCommand("Handle termination example");
    rootCommand.Add(urlOption);

    rootCommand.SetHandler(async (context) =>
        {
            string? urlOptionValue = context.ParseResult.GetValueForOption(urlOption);
            var token = context.GetCancellationToken();
            returnCode = await DoRootCommand(urlOptionValue, token);
        });

    await rootCommand.InvokeAsync(args);

    return returnCode;
}

public static async Task<int> DoRootCommand(
    string? urlOptionValue, CancellationToken cancellationToken)
{
    try
    {
        using (var httpClient = new HttpClient())
        {
            await httpClient.GetAsync(urlOptionValue, cancellationToken);
        }
        return 0;
    }
    catch (OperationCanceledException)
    {
        Console.Error.WriteLine("The operation was aborted");
        return 1;
    }
}

上記のコードでは、1 つ以上の IValueDescriptor<T> オブジェクトではなく、InvocationContext インスタンスを取得する SetHandler オーバーロードを使用します。 InvocationContext は、CancellationTokenParseResult オブジェクトを取得するために使用されます。 ParseResult には、引数またはオプションの値を指定できます。

サンプル コードをテストするには、読み込みに少し時間がかかる URL を指定してコマンドを実行し、読み込みが完了する前に Ctrl+C を押します。 macOS の場合は、Command+ピリオド (.) を押します。 たとえば、次のように入力します。

testapp --url https://learn.microsoft.com/aspnet/core/fundamentals/minimal-apis
The operation was aborted

また、キャンセル アクションを CancellationToken.Register メソッドを使って直接追加することもできます。

プロセスの終了コードを設定する別の方法については、「終了コードを設定する」を参照してください。

関連項目

System.CommandLine の概要