C#事件的奇怪之处
Weird things with C# events
我正在学习事件和委托,并决定编写这样的控制台应用程序。
程序应该每 3 秒和 5 秒向我发送消息。但它什么也没做。
我有一个 class WorkingTimer
:
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 Form Application 中制作完全相同的程序并且效果很好。区别仅在于定时器事件 Elapsed 和 Tick。
我做错了什么?
程序在 Main
函数结束时退出。尝试添加一个虚拟 Console.ReadLine()
以保持它 运行.
结果代码为:
static void Main(string[] args)
{
WorkingTimer wt = new WorkingTimer();
wt.Every3Seconds += wt_Every3Seconds;
wt.Every5Seconds += wt_Every5Seconds;
Console.ReadLine();
}
我正在学习事件和委托,并决定编写这样的控制台应用程序。 程序应该每 3 秒和 5 秒向我发送消息。但它什么也没做。
我有一个 class WorkingTimer
:
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 Form Application 中制作完全相同的程序并且效果很好。区别仅在于定时器事件 Elapsed 和 Tick。
我做错了什么?
程序在 Main
函数结束时退出。尝试添加一个虚拟 Console.ReadLine()
以保持它 运行.
结果代码为:
static void Main(string[] args)
{
WorkingTimer wt = new WorkingTimer();
wt.Every3Seconds += wt_Every3Seconds;
wt.Every5Seconds += wt_Every5Seconds;
Console.ReadLine();
}