Is there a timer class in C# that isn't in the Windows.Forms namespace?

后端 未结 6 1307

I want to use a timer in my simple .NET application written in C#. The only one I can find is the Windows.Forms.Timer class. I don\'t want to reference this namespace just f

6条回答
  •  太阳男子
    2020-12-30 03:53

    I would recommend the Timer class in the System.Timers namespace. Also of interest, the Timer class in the System.Threading namespace.

    using System;
    using System.Timers;
    
    public class Timer1
    {
        private static Timer aTimer = new System.Timers.Timer(10000);
    
        public static void Main()
        {
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Enabled = true;
    
            Console.WriteLine("Press the Enter key to exit the program.");
            Console.ReadLine();
        }
    
        // Specify what you want to happen when the Elapsed event is 
        // raised.
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
        }
    }
    

    Example from MSDN docs.

提交回复
热议问题