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

时间:2019-03-31 13:21:59

标签: c# .net-core sigint

让我们考虑一下这个简短的演示:

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");
}

如您所见,程序正在等待取消事件,表明它不希望关闭,等待一秒钟,打印“主机完成”并退出。

我希望输出为:

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错误?

1 个答案:

答案 0 :(得分:0)

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