2014-02-23 28 views
0
using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using System.Threading.Tasks; 
    using System.Timers; 

     namespace ConsoleApplication1 
     { 
      class Program 
      { 
       static void Main(string[] args) 
       { 
        Timer time = new Timer(); 
        time.Elapsed += new ElapsedEventHandler(action); 
        time.Interval = 5000; 
        time.Enabled = true; 

        time.Start(); 


       } 

       static void action(Object sender, ElapsedEventArgs args) 
       { 
        Console.WriteLine("haha\n"); 
       } 

      } 
     } 

這段代碼沒有任何輸出。誰能告訴我問題是什麼?非常感謝你。我遵循MSDN上的確切代碼。http://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.71).aspx如何從這段代碼中得不到輸出?

+0

我用CTRL + F5。沒有輸出 –

+1

while(true){} after time.Start();將保持循環。 – Andy

回答

1

計時器立即超出範圍,因此永遠不會被調用。程序在有機會觸發該操作之前退出。

您可以通過time.start()後加入這個讓你的主要方法睡眠:

TimeSpan interval = new TimeSpan(0, 0, 2); 
Thread.Sleep(interval); 
+0

它等待多少秒? – rene

+0

使用線程需要我添加線程類,但我正在使用系統計時器。 –

+0

TimeSpan interval = new TimeSpan(0,0,2); System.Threading.Thread.Sleep(interval); –

0
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Timers; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     while(true) 
     { 

     Timer time = new Timer(); 
     time.Elapsed += new ElapsedEventHandler(action); 
     time.Interval = 100; 
     time.Enabled = true; 

     time.Start(); 
     string line = Console.ReadLine(); // Get string from user 
     if (line == "exit") // Check for exit condition 
     { 
      break; 
     } 

    } 
    Console.WriteLine("End of Program\n"); 

} 

static void action(Object sender, ElapsedEventArgs args) 
{ 
    Console.WriteLine("haha\n"); 
} 

} 
相關問題