C# 捕获取消事件后程序未完成

C# 捕获取消事件后程序未完成,c#,event-handling,task,cancellation,C#,Event Handling,Task,Cancellation,为什么按下Ctrl+C时此控制台应用程序不退出 程序输出: Press Ctrl+C to stop... doing stuff. doing stuff. ... *Ctrl+C pressed* exiting... *never actually exits* 您需要将ConsoleCancelEventArgs.Cancel属性设置为true: Console.CancelKeyPress += (sender, e) => { tcs.SetResult(null)

为什么按下Ctrl+C时此控制台应用程序不退出

程序输出:

Press Ctrl+C to stop...
doing stuff.
doing stuff.
...
*Ctrl+C pressed*
exiting...
*never actually exits*


您需要将
ConsoleCancelEventArgs.Cancel
属性设置为
true

Console.CancelKeyPress += (sender, e) =>
{
    tcs.SetResult(null);
    e.Cancel = true;   // <-------- add this to your code
};
Console.CancelKeyPress+=(发送方,e)=>
{
tcs.SetResult(空);

e、 Cancel=true;//这不是更像ctrl-D吗?不,
Task.Run
在不等待的情况下调用异步代码。即使我完全注释掉while循环,它仍然挂起…Downvoter-请解释。这确实解决了复制问题和OP的原始问题。这正是我遇到和推断的问题。很遗憾,我没有找到你的答案,这会节省我一些时间。此外,它不仅仅是在没有调试的情况下运行,还使用windows cmd,在没有完成的情况下终止(不优雅),这让我觉得我在取消活动中遗漏了一些东西。无论如何,我正在向上投票,这样其他人也会看到它,我会尝试编辑问题。
public class MyAsyncClass {
    public async Task Start() {
        while(true) {
            await Console.Out.WriteLineAsync("doing stuff.");
            Thread.Sleep(1000);
        }
    }
}
Console.CancelKeyPress += (sender, e) =>
{
    tcs.SetResult(null);
    e.Cancel = true;   // <-------- add this to your code
};