簡體   English   中英

為什么這個短程序永遠不會完成?

[英]Why does this short program never complete?

通過調試我自己的問題,我設法重新創建了一個非常不尋常的小程序:

using System;
using System.Threading;

namespace CancelBug
{
    class Program
    {
        static void Main(string[] args)
        {
            var unused = new ManualResetEvent(false);
            var cancelled = new ManualResetEvent(false);
            Console.CancelKeyPress += (s, e) => cancelled.Set();
            Console.WriteLine("Running. The only thing to do now is ctrl+c or close the window...");
            WaitHandle.WaitAny(new[] { unused, cancelled });
            Console.WriteLine("Press enter to continue...");
            Console.Read();
        }
    }
}

我希望這個程序能夠:

  • 顯示第一行
  • 等到用戶嘗試退出程序
  • 顯示第二行
  • 等到用戶按下回車鍵
  • 出口

但是,一旦這使它通過對WaitHandle.WaitAny ,它似乎掛在隨機行上。 有時最后一行永遠不會被打印出來,有時它會被打印,但是輸入鍵永遠不會被讀取。 使用更大的代碼庫,它可以執行更多代碼行,並且仍然掛在看似隨機的位置。

誰能解釋這種奇怪的行為?

您需要取消CTRL+C命令,否則您的進程將被終止:

Console.CancelKeyPress += (s, e) =>
{
    e.Cancel = true;
    cancelled.Set();
};

來自https://msdn.microsoft.com/en-us/library/system.consolecanceleventargs(v=vs.110).aspx

如果在事件處理程序中將Cancel屬性設置為true,則恢復該進程; 否則,該過程終止。 默認情況下,ConsoleCancelEventArgs屬性的值為false,並且該進程終止。

Ctrl + C是關閉命令窗口的全局命令。 因此,此組合鍵將在實際程序結束之前關閉窗口。 嘗試使用其他密鑰。

請在沒有調試器的情況下運行應用程序(直接從命令行)。

根據我的測試,這是我的測試應用程序,其行為與您期望的一樣。

        var cancelled = new ManualResetEvent(false);
        Console.CancelKeyPress += (s, e) =>
        {
            e.Cancel = true;
            Console.WriteLine("Ctrl+C detected...");
            cancelled.Set();
        };
        Console.WriteLine("Running. The only thing to do now is ctrl+c or close the window...");
        WaitHandle.WaitAny(new[] { cancelled });
        Console.WriteLine("Press enter to exit...");
        Console.ReadLine();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM