如何在 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;
    }
}

前面的代码使用一个 SetHandler 重载来获取 InvocationContext 实例而不是一个或多个 IValueDescriptor<T> 对象。 InvocationContext 用于获取 CancellationTokenParseResult 对象。 ParseResult 可以提供参数或选项值。

若要测试示例代码,请使用需要一些时间加载的 URL 运行命令,并在完成加载之前按 Ctrl+C。 在 macOS 上,按 Command+Period(.)。 例如:

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

还可使用 CancellationToken.Register 方法直接添加取消操作。

有关设置进程退出代码的替代方法,请参阅设置退出代码

请参阅

System.CommandLine 概述