CancelKeyPress 处理程序混淆了 shell(cmd.exe、powershell 和 bash)

CancelKeyPress handler confuses shells (cmd.exe, powershell, and bash)

让我们来看看这个简短的演示:

private static readonly CancellationTokenSource CancelSource = new CancellationTokenSource();

public static void Main()
{
    Console.WriteLine("Hello world!");
    Console.CancelKeyPress += (s, e) =>
    {
        e.Cancel = true;
        CancelSource.Cancel();
        Console.WriteLine("CancelKeyPress event handler finished");
    };
    CancelSource.Token.WaitHandle.WaitOne();
    Task.Delay(1000).Wait();
    Console.WriteLine("Main finished");
}

可以看到,程序在等待cancel事件,声明不想关机,等一秒,打印"Main finished"退出。

我希望输出为:

C:\Users\Benni\source\repos\Test\Test>dotnet run
Hello world!
CancelKeyPress event handler finished
^C
Main finished
C:\Users\Benni\source\repos\Test\Test>

但它是:

C:\Users\Benni\source\repos\Test\Test>dotnet run
Hello world!
CancelKeyPress event handler finished
^C
C:\Users\Benni\source\repos\Test\Test>Main finished

不幸的是,shell(我测试了 bash、cmd.exe 和 powershell)在程序实际完成之前就打印了 CWD(用于下一个命令)运行!我错过了什么吗?我必须使用 Console.TreatControlCAsInput,还是这是一个 coreclr 错误?

这确实是一个 dotnet cli 问题:https://github.com/dotnet/cli/issues/11050