我想在用C#编写的简单.NET应用程序中使用计时器。我唯一能找到的是Windows.Forms.Timer类。我不想只为我的控制台应用程序引用这个名称空间。
是否有用于控制台应用程序的C# timer (或类似timer )类?
发布于 2008-10-03 23:39:02
System.Timers.Timer
正如MagicKat所说:
System.Threading.Timer
你可以在这里看到区别:http://intellitect.com/system-windows-forms-timer-vs-system-threading-timer-vs-system-timers-timer/
你可以在这里看到MSDN的例子:
http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx
还有这里:
http://msdn.microsoft.com/en-us/library/system.threading.timer(VS.80).aspx
发布于 2008-10-03 23:41:53
我推荐System.Timers
名称空间中的Timer
类。同样值得关注的是System.Threading
名称空间中的Timer
类。
using System;
using System.Timers;
public class Timer1
{
private static Timer aTimer = new System.Timers.Timer(10000);
public static void Main()
{
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
}
来自MSDN文档的示例。
发布于 2010-08-01 18:10:28
据我所知,至少还有System.Timers.Timer和System.Threading.Timer类。
但有一件事需要注意(如果你以前还没有这样做过),假设你已经在你的using子句中有了System.Threading命名空间,但是你实际上想要在System.Timers中使用计时器,你需要这样做:
using System.Threading;
using Timer = System.Timers.Timer;
Jon Skeet在他的多线程指南中有一篇关于定时器的文章,非常值得一读:http://www.yoda.arachsys.com/csharp/threads/timers.shtml
https://stackoverflow.com/questions/169332
复制相似问题