关于C#事件的奇怪事情
我正在学习事件和委托,并决定编写这样的控制台应用程序。 程序应每3秒和5秒向我发送一次消息。但它什么也没用 我有一个类关于C#事件的奇怪事情,c#,events,delegates,C#,Events,Delegates,我正在学习事件和委托,并决定编写这样的控制台应用程序。 程序应每3秒和5秒向我发送一次消息。但它什么也没用 我有一个类工作计时器: class WorkingTimer { private Timer _timer = new Timer(); private long _working_seconds = 0; public delegate void MyDelegate(); public event MyDelegate Every3Seconds;
工作计时器:
class WorkingTimer
{
private Timer _timer = new Timer();
private long _working_seconds = 0;
public delegate void MyDelegate();
public event MyDelegate Every3Seconds;
public event MyDelegate Every5Seconds;
public WorkingTimer()
{
_timer.Interval = 1000;
_timer.Elapsed += _timer_Elapsed;
_timer.Start();
}
void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
_working_seconds++;
if (Every3Seconds != null && _working_seconds % 3 == 0)
Every3Seconds();
if (Every5Seconds != null && _working_seconds % 5 == 0)
Every5Seconds();
}
}
实际上,这个节目:
class Program
{
static void Main(string[] args)
{
WorkingTimer wt = new WorkingTimer();
wt.Every3Seconds += wt_Every3Seconds;
wt.Every5Seconds += wt_Every5Seconds;
}
static void wt_Every3Seconds()
{
Console.WriteLine("3 seconds elapsed");
}
static void wt_Every5Seconds()
{
Console.WriteLine("5 seconds elapsed");
}
}
所以,当我运行时,它什么也不做。但我尝试在Windows窗体应用程序中制作完全相同的程序,效果非常好。区别仅在于计时器事件已过和滴答声
我做错了什么?程序在主功能的末尾退出。尝试添加一个虚拟的Console.ReadLine()
以保持其运行
由此产生的代码将是:
static void Main(string[] args)
{
WorkingTimer wt = new WorkingTimer();
wt.Every3Seconds += wt_Every3Seconds;
wt.Every5Seconds += wt_Every5Seconds;
Console.ReadLine();
}
可能程序在Main
功能结束时关闭。。。您是否尝试在Main
的末尾添加一个虚拟的Console.ReadLine()
?是的。伟大的非常感谢。