如何用C#写出每隔一秒钟输出一个值的函数?

解决方案 »

  1.   

    while(true)
    {
        Thread.Sleep(1000);
        //下面执行函数。
    }
      

  2.   

    private Timer m_Timer; m_Timer = new Timer(); 
    m_Timer.Interval = 1000; 
    m_Timer.Tick += new EventHandler(m_Timer_Tick); 
    m_Timer.Start();  void m_Timer_Tick(object sender, EventArgs e) 

          }        
      

  3.   


    using System;
    using System.Threading;class TimerExample
    {
        static void Main()
        {
            AutoResetEvent autoEvent     = new AutoResetEvent(false);
            StatusChecker  statusChecker = new StatusChecker(10);        // Create the delegate that invokes methods for the timer.
            TimerCallback timerDelegate = 
                new TimerCallback(statusChecker.CheckStatus);        // Create a timer that signals the delegate to invoke 
            // CheckStatus after one second, and every 1/4 second 
            // thereafter.
            Console.WriteLine("{0} Creating timer.\n", 
                DateTime.Now.ToString("h:mm:ss.fff"));
            Timer stateTimer = 
                    new Timer(timerDelegate, autoEvent, 1000, 250);        // When autoEvent signals, change the period to every 
            // 1/2 second.
            autoEvent.WaitOne(5000, false);
            stateTimer.Change(0, 500);
            Console.WriteLine("\nChanging period.\n");        // When autoEvent signals the second time, dispose of 
            // the timer.
            autoEvent.WaitOne(5000, false);
            stateTimer.Dispose();
            Console.WriteLine("\nDestroying timer.");
        }
    }class StatusChecker
    {
        int invokeCount, maxCount;    public StatusChecker(int count)
        {
            invokeCount  = 0;
            maxCount = count;
        }    // This method is called by the timer delegate.
        public void CheckStatus(Object stateInfo)
        {
            AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
            Console.WriteLine("{0} Checking status {1,2}.", 
                DateTime.Now.ToString("h:mm:ss.fff"), 
                (++invokeCount).ToString());        if(invokeCount == maxCount)
            {
                // Reset the counter and signal Main.
                invokeCount  = 0;
                autoEvent.Set();
            }
        }
    }
    msdn里的一段代码,给你参考一下
      

  4.   

    用timer控件的,tick事件,你能得到你想要的东西。