Why CancellationTokenSource hangs an application

前端 未结 1 1029
轻奢々
轻奢々 2021-01-15 04:50

Here is simple code piece that hangs and never ends:

public static void Main()
{
    using (var cancellationTokenSource = new CancellationTokenSource())
             


        
相关标签:
1条回答
  • 2021-01-15 05:02

    The issue is not your cancellation token, it's the fact that you chose to test with CancelKeyPress. When this event happens, you get given the ConsoleCancelEventArgs, which has a Cancel property:

    Gets or sets a value that indicates whether simultaneously pressing the Control modifier key and the C console key (Ctrl+C) or the Ctrl+Break keys terminates the current process. The default is false, which terminates the current process.

    Since you're not setting it to true, your application terminates after the event handler has finished running. Depending on exactly what's going on at the time, it seems that sometimes the cancellation token has time to break out of the while loop, other times it doesn't:

    test runs

    Your original code can be fixed as follows:

    public static void Main()
    {
        using (var cancellationTokenSource = new CancellationTokenSource())
        {
            Console.CancelKeyPress += (_, ccea) => {
                cancellationTokenSource.Cancel();
                ccea.Cancel = true; //cancel the cancel.  There's too many cancels!
            };
            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");
    }
    
    0 讨论(0)
提交回复
热议问题