C# console timer
Written by: maffelu , 2011-06-08
using System;
using System.Threading;
namespace EventHandling
{
public delegate void TickDelegate();
public class CustomTimer
{
#region Events
/// <summary>
/// The tick event, will be triggered on every tick.
/// </summary>
public event TickDelegate Tick;
#endregion
#region Fields
private Timer m_Timer;
#endregion
#region Properties
/// <summary>
/// The period between the ticks
/// </summary>
public int Period { get; set; }
/// <summary>
/// The time to delay before the callback is invoked
/// </summary>
public int DueTime { get; set; }
#endregion
#region Construct
public CustomTimer() : this(0, 0) { }
public CustomTimer(int period) : this(period, 0) { }
public CustomTimer(int period, int dueTime)
{
Period = period;
DueTime = dueTime;
}
#endregion
#region Methods
protected void OnTick()
{
if (Tick != null)
{
Tick();
}
}
/// <summary>
/// Start the timer
/// </summary>
public void Start()
{
TimerCallback timerCallback = new TimerCallback(ProcessTimerCallback);
m_Timer = new Timer(
timerCallback,
null,
DueTime,
Period
);
}
/// <summary>
/// Stop the timer
/// </summary>
public void Stop()
{
if (m_Timer != null)
{
m_Timer.Dispose();
m_Timer = null;
}
}
private void ProcessTimerCallback(object o)
{
OnTick();
}
#endregion
}
}
using System;
using System.Threading;
namespace EventHandling
{
class Program
{
static void Main(string[] args)
{
CustomTimer timer = new CustomTimer(500, 1000);
timer.Tick = new TickDelegate(timer_Tick);
timer.Start();
Thread.Sleep(5000);
timer.Stop();
Console.WriteLine("Timer stopped...");
Console.Read();
}
static void timer_Tick()
{
Console.WriteLine("Test!");
}
}
}
There are no comments on this article.
If you have any question or just want to leave a message, just fill out the form below!
Your e-mail will not be visible in your post, it is for validation reasons only
Maffelu
Creator and admin of MorkaLork.com.
Started programming in HTML back when frames and tables was the way to design a page, moved on to Pascal/Delphi, PHP, javascript/jQuery, VB.NET/C#, Java and C++.
Currently studies .NET (in general) focusing on ASP.NET.