using System; using System.Threading; class Program { static void Main(string[] args) { Console.WriteLine("Started."); Timer timer = new Timer(DoWork, null, 0, 2000); Console.ReadLine(); } static void DoWork(object state) { Console.WriteLine("Task executed at: " + DateTime.Now); } }
using System; using System.Threading; class Program { static Timer timer; static void Main(string[] args) { Console.WriteLine("Started."); timer = new Timer(DoWork, null, 0, 2000); Console.ReadLine(); timer.Dispose(); Console.WriteLine("Stopped."); } static void DoWork(object state) { Console.WriteLine("Task executed at: " + DateTime.Now); } }This code creates a timer that runs indefinitely until the user presses a key. Once a key is pressed, the timer is stopped using the Dispose() method. The package library for System.Threading is part of the .NET Framework Class Library, which is included with the Microsoft .NET Framework SDK.