【问题标题】:10 minutes timer in C#C#中的10分钟计时器
【发布时间】:2016-11-06 14:07:20
【问题描述】:

我正在开发一个 C# 控制台应用程序,我需要添加一个计时器,该计时器在我写“开始”时启动,并在 10 分钟后自动停止。 如何仅使用“static void Main()”来做到这一点?

我有这个:

using System;
using System.Timers;

namespace myScript
{
    class Program
    {
        static void Main()
        {
            string getInput = Console.ReadLine();

            if (getInput == "start")
            {
                //start timer
            }

            if (//10 minutes have passed)
            {
                //do something
            }
        }
    }
}

谢谢!

【问题讨论】:

  • 定义主类 ...并展示你已经尝试过/拥有的东西。你的问题是这样的:我需要一个可以运行xy 的程序,你能帮我写出来吗?
  • 我需要更多信息才能为您提供帮助。输入 start 后会发生什么?应用程序应该阻止吗?是否可以启动多个计时器?
  • @Jonas 谢谢!我刚刚编辑了问题。

标签: c# timer console-application


【解决方案1】:
//start timer
//put this into your if statement
Timer timer = new Timer (1000 * 60 * 10);
timer.Elapsed += delegate (object sender, EventArgs e) 
{
    //do something
    timer.Stop ();
    timer.Dispose ();
};
timer.Start ();

试试这个,使用 system.timers 而不是线程。这应该启动 10 分钟计时器,它会做一些事情并在操作结束时自行处理。

【讨论】:

    【解决方案2】:
        using System;
        using System.Threading;
    
    static void Main(string[] args)
                {
                    Console.WriteLine("Please type \"start\" and press ENTER");
                    while (true)
                    {
                        var userInput = Console.ReadLine();
    
                        if (userInput.Equals("start"))
                        {
                            break;
                        }
                        Console.WriteLine("Not correct, please try again");
                    }
    
    
                    var minutes = 10;
                    Console.WriteLine("Going to sleep for " + minutes + " Minutes...");
                    Thread.Sleep(1000 * minutes * 60);
    
                    Console.WriteLine("Done...");
    
                    Console.ReadLine();
                }
    

    【讨论】:

    • 我必须在顶部添加“使用”的东西吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多