使用随机用户输入停止正在运行的计时器

时间:2018-05-18 09:35:20

标签: c#

我目前正在尝试计时器。 我做了一个计时器,倒计时5秒,然后关闭程序。

然而,在按下随机密钥时,我似乎无法弄清楚如何中断并停止计时器关闭程序。

但我缺少像Timer.Stop()

这样的函数
    private static void CommandExit()
    {
        Console.WriteLine("Thank you for your input!");
        Console.WriteLine("The programm will now close. \r\n");
        var countdown = 5;
        var myTimer = new Timer(state =>
        {
            Console.WriteLine("Program is closing in: '{0}' ", countdown);
            countdown--;
             if (countdown <= 0)
            {
                Environment.Exit(0);
            }
            if (countdown != null)
            {
                Console.WriteLine("Press any Key to interrupt the closing process.");
                var breakuptoken = Console.ReadKey();
                if (breakuptoken != null)
                {
                //SOMETHING IS MISSING HERE
                }
            }
        }, null,0, 1000);

    }

解决方案:

private static void CommandExit()
    {
        var countdown = 5;
        Console.WriteLine("Thank you for your input!");
        Console.WriteLine("The programm will now close. \r\n");
        Console.WriteLine("Press any Key to interrupt the closing process.");
        var myTimer = new Timer(state =>
        {
        Console.WriteLine("Program is closing in: '{0}' ", countdown);
            countdown--;
        if (countdown <= 0)
        {
            Environment.Exit(0);
        }

        }, null, 0, 1000);
        Console.ReadKey();
        myTimer.Change(Timeout.Infinite, Timeout.Infinite);          
    }

2 个答案:

答案 0 :(得分:1)

这取决于您使用的计时器类型:

System.Windows.Forms.Timer:timer.Enabled = false;
System.Threading.Timer:timer.Change(Timeout.Infinite, Timeout.Infinite);
System.Timers.Timer:timer.Enabled = false;timer.Stop();

特定于您的用例的解决方案:

class Program
{
    static void Main(string[] args)
    {
        CommandExit();
        Console.ReadLine();
    }

        private static void CommandExit()
    {
        var countdown = 5;
        Console.WriteLine("Thank you for your input!");
        Console.WriteLine("The programm will now close. \r\n");
        Console.WriteLine("Press any Key to interrupt the closing process.");
        var myTimer = new Timer(state =>
        {
            Console.WriteLine("Program is closing in: '{0}' ", countdown);
            countdown--;
            if (countdown <= 0)
            {
                Environment.Exit(0);
            }
        }, null, 0, 1000);
        Console.ReadKey();
        myTimer.Change(Timeout.Infinite, Timeout.Infinite);          
    }
}

答案 1 :(得分:0)

使用

myTimer.cancel();
myTimer.purge();