Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Environment.Exit() deadlocks after context.GetCancellationToken() #2091

Closed
CodeCasterNL opened this issue Mar 14, 2023 · 1 comment
Closed
Assignees

Comments

@CodeCasterNL
Copy link

When code calls context.GetCancellationToken() to pass that token to a handler's logic and that logic (or other code outside caller's control) calls Environment.Exit(), the application deadlocks.

This is caused by CancelOnProcessTermination() subscribing to the CancellationHandlingAdded event.

Repro on version 2.0.0-beta4.22272.1:

using System.CommandLine;

var rootCommand = new RootCommand();

var testCommand = new Command("test", "Test command");

testCommand.SetHandler(async context =>
{
    await ExitAsync(context.GetCancellationToken());
});

rootCommand.AddCommand(testCommand);

await rootCommand.InvokeAsync(args);

static Task ExitAsync(CancellationToken cancellationToken)
{
    Console.WriteLine("Exiting...");

    // This hangs
    Environment.Exit(-1);

    // This is ignored
    return Task.CompletedTask;
}

If you comment out the Environment.Exit, the application exits successfully. When it's present, it indefinitely hangs there.

@adamsitnik
Copy link
Member

Hi @CodeCasterNL

Thank you for a detailed bug report with a repo!

The bug has been fixed, most likely by #2044

static async Task Main(string[] args)
{
    var rootCommand = new RootCommand();

    var testCommand = new Command("test", "Test command");

    testCommand.SetAction((context, cancellationToken) => ExitAsync(cancellationToken));

    rootCommand.Subcommands.Add(testCommand);

    await rootCommand.Parse(args).InvokeAsync();

    static Task ExitAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine("Exiting...");

        // This hangs
        Environment.Exit(-1);

        // This is ignored
        return Task.CompletedTask;
    }
}

In the next few weeks we are going to release a new nuget package to nuget.org.

@adamsitnik adamsitnik self-assigned this Mar 28, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants