Kur*_*ami 1 .net c# 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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用计时器而不是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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1601 次 |
| 最近记录: |