为什么我从这段代码中得不到输出?

时间:2014-02-23 23:18:48

标签: c#

    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

2 个答案:

答案 0 :(得分:1)

定时器立即超出范围,因此永远不会被调用。程序在有机会解雇之前退出。

您可以在time.start()

之后添加此方法,让您的主方法进入睡眠状态
TimeSpan interval = new TimeSpan(0, 0, 2);
Thread.Sleep(interval);

答案 1 :(得分: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");
}

}