繁体   English   中英

C#计时器在X秒钟后关闭控制台窗口

[英]C# Timer to close Console Window after X seconds

纽伯在这里。

我试图了解如何编写计时器以关闭我的c#控制台应用程序,这样我就不必再次按下“返回”键来关闭窗口(我一直在使用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();

    }
}

}

我已经研究了一些内容,我去了为那些了解这些东西和新手的人们而写的Microsoft资源,他们看了一些博客,却变得越来越困惑。 希望能有所帮助,对此深表感谢。

总结一下-我只希望控制台窗口在5秒后自动关闭。 这就是我正在尝试使用的一种简单方法。 最终,我将尝试在全班学习或做一些类似的事情,但是我需要逐步进行,以便理解。

干杯

Thread.Sleep将做您想要的:

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

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

我相信这应该做到:

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();
        }
    }
}

(请注意,它不是来自名称空间System.TimersTimer类,而是来自名称空间System.Threading

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

带支票的职位是正确的答案。 但是,我只是想明确使用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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM