C#事件的奇怪之处

时间:2015-06-25 14:55:47

标签: c# events delegates

我正在学习事件和代表,并决定编写这样的控制台应用程序。 程序应该每隔3和5秒给我发消息。但它没有做任何事情。

我有一个班级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中制作完全相同的程序,它运行得很好。区别仅在于Timer事件Elapsed和Tick。

我做错了什么?

1 个答案:

答案 0 :(得分:3)

程序在Main功能结束时退出。尝试添加虚拟Console.ReadLine()以使其保持运行。

结果代码为:

static void Main(string[] args)
{
    WorkingTimer wt = new WorkingTimer();
    wt.Every3Seconds += wt_Every3Seconds;
    wt.Every5Seconds += wt_Every5Seconds;
    Console.ReadLine();
}