2015-06-25 102 views
1

我正在學習事件和代表,並決定寫這樣的控制檯應用程序。 程序應該每3秒和5秒給我發消息。但它沒有做任何事情。奇怪的事情與C#事件

我有一個類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窗體應用程序中製作完全相同的程序,並且效果很好。區別僅在於計時器事件已經發生並且滴答。

我到底做錯了什麼?

+0

也許程序在'Main'函數結束時關閉...你嘗試加入的虛擬'到Console.ReadLine()'在結束'Main'? – aochagavia

回答

3

程序在Main函數結束時退出。嘗試添加一個虛擬Console.ReadLine()以保持其運行。

產生的代碼將是:

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

是的。大。謝謝。 – YTerle