C#Timer在X秒后关闭控制台窗口

时间:2014-01-19 19:04:03

标签: c# timer console

newb here。

我试图了解如何编写一个计时器来关闭我的c#控制台应用程序,以便我不必再次点击'return'来关闭窗口(我一直在使用Console.Read();保持它打开所以我可以看到应用程序按目的运行到目前为止)所以我正在尝试制作一个小计时器方法,下面是我发现的远,但它不运行,因为我不明白什么/我认为如何处理它。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lec044b_ForLoop_Sum
{
class Program
{
    public void Play()
    {
        Console.WriteLine("Announce Program");






        Console.WriteLine("Close Program Announcement");

        timer1_Tick(3000);


    }


    private void timer1_Tick(object sender, EventArgs e)
    {
        this.Close();
    }



    static void Main(string[] args)
    {
        Program myProgram = new Program();
        myProgram.Play();

    }
}

}

我已经研究了一些,我已经去了微软资源,这些资源是为那些了解这些东西和新手的人写的,并且看了几个博客并且变得越来越困惑。希望得到一些帮助,这是值得赞赏的。

总结一下 - 我只希望我的控制台窗口在5秒后自动关闭。这就是我想用一个简单的方法做的事情。最终我会尝试将其作为一个类或类似的东西,但我需要小步骤,所以我理解。

干杯

4 个答案:

答案 0 :(得分:6)

Thread.Sleep会做你想做的事:

static void Main(string[] args)
{
    Play();
}

static void Play()
{
    Console.WriteLine("Announce Program");
    Console.WriteLine("Close Program Announcement");
    Thread.Sleep(5000);            
}

答案 1 :(得分:1)

我相信这应该做到:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Lec044b_ForLoop_Sum
{
    class Program
    {
        public void Play()
        {
            Console.WriteLine("Announce Program");
            Console.WriteLine("Close Program Announcement");
            Timer t = new Timer(timerC, null, 5000, 5000);
        }

        private void timerC(object state)
        {
            Environment.Exit(0);
        }

        static void Main(string[] args)
        {
            Program myProgram = new Program();
            myProgram.Play();
            Console.ReadLine();
        }
    }
}

(注意它不是来自命名空间Timer的{​​{1}}类,而是来自命名空间System.Timers

答案 2 :(得分:0)

  Timer t = new Timer() ;
        t.Interval = 120000;
        t.Tick += (s, e) =>
        {
            Application.Exit();
        };
        t.Start();

答案 3 :(得分:0)

带有支票的帖子是正确的答案。但是,我只是想明确使用System.Threading.Timer! 我有一个类似的问题,一个System.Timers.Timer和一个System.Windows.Forms.Timer,而没有锁定UI的唯一对我来说完美的问题是System.Threading.Timer。 我的实现如下。

using System.Threading;

System.Threading.Timer timer = new System.Threading.Timer(timerC, null, 5000, 5000);

private void timerC(object state)
{
    Environment.Exit(0);
}
相关问题