这里是一个简单的代码片段,它会挂起并永远不会结束:
public static void Main()
{
using (var cancellationTokenSource = new CancellationTokenSource())
{
Console.CancelKeyPress += (_, __) =>
cancellationTokenSource.Cancel();
while (!cancellationTokenSource.Token.WaitHandle.WaitOne(1000))
{
Console.WriteLine("Still running...");
}
Console.WriteLine("Cancellation is requested. Trying to dispose cancellation token...");
}
Console.WriteLine("Just before close");
}
问题是
Just before close
这行代码从未被执行。我的第一个想法是“可能是因为在KeyPress上的闭包”,因此我以以下方式重写了它:public static void Main()
{
using (var cancellationTokenSource = new CancellationTokenSource())
{
void Foo(object sender, ConsoleCancelEventArgs consoleCancelEventArgs)
{
cancellationTokenSource.Cancel();
}
Console.CancelKeyPress += Foo;
while (!cancellationTokenSource.Token.WaitHandle.WaitOne(1000))
{
Console.WriteLine("Still running...");
}
Console.WriteLine("Cancellation is requested. Unsubscribing...");
Console.CancelKeyPress -= Foo;
Console.WriteLine("Cancellation is requested. Trying to dispose cancellation token...");
}
Console.WriteLine("Just before close");
}
但现在它停留在取消订阅
阶段...
你知道为什么会出现这种情况吗?我想在控制台应用程序中运行一些后台任务并等待其完成,但由于上述原因,我的应用程序已经崩溃了。
CancelKeyEvent
会让事情变得混乱。 - undefinedConsole.CancelKeyPress
和AssemblyLoadContext.Default.Unloading
来处理SIGTERM信号。 - undefinedCancelKeyPress
相同的问题,Visual Studio会显示下一条语句(黄色箭头),但选择不执行它,永远。应用程序将永远不会终止。对我来说,ccea.Cancel = true
解决了这个问题。 - undefined