c# - 在 C# 中检查每分钟的时间

标签 c# .net visual-studio

我正在制作一个应用程序,每 1、5 或 30 分钟甚至每小时通知一次用户。 例如用户在5:06打开程序,程序会在6:06通知用户。

所以我当前的代码是使用 Thread.Sleep() 函数每 5 分钟通知一次用户,但我发现它有点蹩脚。

这是我的代码:

public void timeIdentifier()
    {
        seiyu.SelectVoiceByHints(VoiceGender.Female);
        while(true)
        {
            string alarm = String.Format("Time check");
            seiyu.Speak(alarm);
            string sayTime = String.Format(DateTime.Now.ToString("h:mm tt"));
            seiyu.Speak(sayTime);
            // It will sleep for 5 minutes LOL
            Thread.Sleep(300000);
        }
    }

最佳答案

您可以使用定时器代替 Thread.Sleep():

public class Program
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {
        aTimer = new System.Timers.Timer(5000); // interval in milliseconds (here - 5 seconds)

        aTimer.Elapsed += new ElapsedEventHandler(ElapsedHandler); // handler - what to do when 5 seconds elaps

        aTimer.Enabled = true;

        // If the timer is declared in a long-running method, use
        // KeepAlive to prevent garbage collection from occurring
        // before the method ends.
        //GC.KeepAlive(aTimer);
    }

    //handler
    private static void ElapsedHandler(object source, ElapsedEventArgs e)
    {
        string alarm = String.Format("Time check");
        seiyu.Speak(alarm);
        string sayTime = String.Format(DateTime.Now.ToString("h:mm tt"));
        seiyu.Speak(sayTime);
    }
}

关于c# - 在 C# 中检查每分钟的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38454349/

相关文章:

c# - try catch block 中的异常优先级

visual-studio - 从Visual Studio项目文件夹中消除所有中间文件的最佳方法?

c# - 使用 msbuild 为 (x86|x64|ARM) 创建 .appxbundle

c# - 什么是枚举,我们可以在哪里使用它?

c# - 创建一个虚拟 HWND 以传递给 Direct3D

c# - 如何将 Arduino 程序移植到 .net 以便在 Netduino 上使用?

.net - 为什么 F# inline 会导致 11 倍的性能提升

c++ - WinRT组件: C1189: #error: "No Target Architecture"

c - Visual Studio C 函数语法错误

c# - HttpResponseMessage.Content.ReasAsString 返回空字符串