C# 使用线程的闹钟。睡眠

C# 使用线程的闹钟。睡眠,c#,alarm,C#,Alarm,这里我有一个闹钟的代码: public static void Main(string[] args) { Console.Write("Seconds: "); int seconds = int.Parse(Console.ReadLine()); System.Threading.Thread.Sleep(seconds * 1000); Timer timer = new Timer(100);

这里我有一个闹钟的代码:

 public static void Main(string[] args)
    {
        Console.Write("Seconds: ");
        int seconds = int.Parse(Console.ReadLine());

        System.Threading.Thread.Sleep(seconds * 1000);

        Timer timer = new Timer(100);

        timer.Elapsed += MakeSound;

        timer.Enabled = true;

        GC.KeepAlive(timer);

        Console.ReadLine();
    }

    private static void MakeSound(object sender, ElapsedEventArgs e)
    {
        Console.Beep();
    }
正如您所看到的,它看起来不太有希望,因为我使用的是Thread.Sleep

如果我使用

Timer Timer=新定时器(秒*1000)而不是
系统.线程.线程.睡眠(秒*1000);


但它不会一直发出嘟嘟声,只在用户按Enter键之前的
秒*1000
秒之间。我能做得更好吗?

如果您查看
System.Threading.Timer
的构造函数重载,您会发现您可以指定
dueTime
,以及
期间:

因此,不要使用
System.Threading.Thread.Sleep(1000*秒)
,而是使用

Timer timer = new Timer(new TimerCallback(MakeSound), null, 1000 * seconds, 100);

不,它在秒发生后每100毫秒(0.1秒)发出一声蜂鸣声,因为这正是您要求它做的。对于“人工”时间跨度,通常最好是a)使用windows任务调度程序,而不是专用程序,或者b)使用更短的睡眠时间,并检查“预期”挂钟时间是否已到(或者现在已过去),而不是试图创建一个持续正确时间的计时器/睡眠。话虽如此,但根本不清楚你想要实现什么。告诉我们你想要它做什么——从这个角度看还不清楚。此外,这对于玩具程序来说是很好的,但是你需要考虑一些其他的东西来获得更精确的时钟。睡1秒至少睡1秒,比如说,超过1秒,还有多少还没有定义。@mikelegg我在试着做一个闹钟。当用户输入一个整数值(秒数)时,它会一直等到这些秒数过去,并每隔0.1秒发出一声蜂鸣声,直到用户按下Enter键。我考了3分。它等了大约3秒钟。然后它发出很大的哔哔声。有什么问题?是不是结尾的嘟嘟声之间的时间不规则?