【发布时间】:2020-06-24 18:03:49
【问题描述】:
我正在寻找一种异步友好的方式来等待 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;
}
}
【问题讨论】:
-
我认为你需要在这里的某个地方“等待”,但我对异步编程的了解不够多,无法提供其他建议。
-
@MikeBruno 我想你错过了这一行:await UntilCancelled().ConfigureAwait(true);
标签: c# visual-studio debugging async-await