gpt4 book ai didi

c# - 在 Visual Studio 2019 调试器中运行时,为什么控制台应用程序在最后一条语句后不退出?

转载 作者:行者123 更新时间:2023-12-04 09:36:25 24 4
gpt4 key购买 nike

我正在寻找一种异步友好的方式来等待 ctrl+c 退出 C# 控制台应用程序。如果我直接运行编译的二进制文件,下面的代码有效。但是,如果我在调试器中运行它,输入 ctrl+c,然后单步执行,我会碰到程序的右大括号,但它不会退出。如果我注释掉等待,应用程序会正常完成,所以我认为这不是 VS 设置问题。

using System;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
public static async Task Main()
{
Console.WriteLine("Hello World");
await UntilCancelled().ConfigureAwait(true);
Console.WriteLine("Goodbye Cruel World");
}

/// <summary>
/// Waits until Ctrl+c or Ctrl+Break is entered into the console
/// </summary>
/// <param name="cancellationToken">A passed in cancellation token can also cause the await to complete</param>
/// <returns>True when cancelled</returns>
public static Task UntilCancelled(CancellationToken cancellationToken = default)
{
var cts = new CancellationTokenSource();
//link tokens if caller wants to have ability to cancel for other conditions
if (default != cancellationToken)
cts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken);

//Attach cancellation to event for exiting the console
Console.CancelKeyPress += (sender, cpe) => cts.Cancel();

var tcs = new TaskCompletionSource<bool>();
cts.Token.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
return tcs.Task;
}
}

最佳答案

尝试这个:

public static Task UntilCancelled(CancellationToken cancellationToken = default)
{
var tcs = new TaskCompletionSource<bool>();
cancellationToken.Register(() => tcs.TrySetResult(true));
Console.CancelKeyPress += (sender, cpe) =>
{
// this will prevent windows from interfering with the shutdown process
cpe.Cancel = true;
tcs.TrySetResult(true);
};

return tcs.Task;
}
我用这个测试了它:
var cts = new CancellationTokenSource();
Console.WriteLine("Started");
Task.Run(async () =>
{
await Task.Delay(5000);
cts.Cancel(false);
}).GetAwaiter();
await Test.UntilCancelled(cts.Token);
Console.WriteLine("Canceled");

关于c# - 在 Visual Studio 2019 调试器中运行时,为什么控制台应用程序在最后一条语句后不退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62561378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com