System.Timer.Timer控件的问题。 System.Timers.Timer aTimer = new System.Timers.Timer(); // Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true; Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine(); // Keep the timer alive until the end of Main.
GC.KeepAlive(aTimer);
尝试了一下,timer是在线等待2秒之后,去执行的回调函数。启动->(2秒后)->执行OnTimedEvent函数->然后每隔两秒执行一次。想问的是,可不可以让timer启动就去执行回调函数,然后再开始重复。就是:启动->执行OnTimedEvent函数->(2秒后)->然后每隔两秒执行一次。
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true; Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine(); // Keep the timer alive until the end of Main.
GC.KeepAlive(aTimer);
尝试了一下,timer是在线等待2秒之后,去执行的回调函数。启动->(2秒后)->执行OnTimedEvent函数->然后每隔两秒执行一次。想问的是,可不可以让timer启动就去执行回调函数,然后再开始重复。就是:启动->执行OnTimedEvent函数->(2秒后)->然后每隔两秒执行一次。
初始化时写好参数就行了,不要用无参数的构造函数
System.Timers.Timer aTimer = new System.Timers.Timer(); // Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
OnTimedEvent(this, ElapsedEventArgs.Empty); // <---- Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine(); // Keep the timer alive until the end of Main.
GC.KeepAlive(aTimer);
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
}
OnTimedEvent(this, ElapsedEventArgs.Empty);是什么意思
函数, so why don't you call it once at the begining?
So what is the difference?
You've got what you want.
actrually, it's not.i want to know how to set "timer" options to what i want
Sure, that is your program :-)
using System.Timers;public class Timer1
{
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer(20000); aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true;
OnTimedEvent(this, ElapsedEventArgs.Empty); //C#在这一句报错了,this指代不明,还有,ElapsedEventArgs向EvenArgs型转化失败 Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
GC.KeepAlive(aTimer);
} private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
}
}
OnTimedEvent(null, null); // it doesn't matter if you don't use those parameters
OnTimedEvent(null, ElapsedEventArgs.Empty); // dittto