TEXT Code:
// < ------------------------------------------------- >
// < XLib.Timer.cs / C#.Net / 18.03.2007 / ZeRoKiLLeR >
// < ------------------------------------------------- >
using System;
using System.Threading;
namespace XLib
{
public class Timer
{
/// <summary>
/// Duration in ms
/// </summary>
private Double m_Duration;
/// <summary>
/// Time left in ms
/// </summary>
private Double m_TimeLeft;
/// <summary>
/// Target method/function after timer finished
/// </summary>
private TargetFunction m_Target;
/// <summary>
/// Tick thread
/// </summary>
private Thread m_TickThread;
/// <summary>
/// State if timer is running
/// </summary>
private Boolean m_Running;
/// <summary>
/// Creates a new timer instance
/// </summary>
/// <param name="duration">Duration in ms</param>
/// <param name="target">Target method/function</param>
public Timer(Double duration, TargetFunction target)
{
try
{
// Set values
this.m_Duration = duration;
this.m_TimeLeft = 0;
this.m_Target = target;
this.m_TickThread = null;
this.m_Running = false;
}
catch (Exception exc)
{
// Handle Errors here
}
}
/// <summary>
/// Starts the timer
/// </summary>
public void Start()
{
try
{
// If timer is not running
if (!this.m_Running)
{
this.m_TickThread = new Thread(new ThreadStart(this.Tick));
this.m_TickThread.Name = "XLib.Timer | Tick-Thread";
this.m_TickThread.Start();
this.m_Running = true;
}
}
catch (Exception exc)
{
// Handle Errors here
}
}
/// <summary>
/// Stopps the timer
/// </summary>
public void Stop()
{
try
{
// If timer is running
if (this.m_Running)
{
// this.m_TickThread.Abort(); -> Throw exception "AbortException" ...
this.m_Running = false; // <- FIX
}
}
catch (Exception exc)
{
// Handle Errors here
}
}
/// <summary>
/// Pause the imer
/// </summary>
public void Pause()
{
try
{
// If timer is running
if (this.m_Running)
{
this.m_Running = false;
}
}
catch (Exception exc)
{
// Handle Errors here
}
}
/// <summary>
/// Tick method
/// </summary>
private void Tick()
{
try
{
// Endless loop
while (true)
{
// If timer is running
if (this.m_Running)
{
if (this.m_TimeLeft < this.m_Duration)
{
this.m_TimeLeft += 100;
}
else
{
this.m_Target.Invoke();
this.m_Running = false;
}
}
// Pause thread for 100ms
Thread.Sleep(TimeSpan.FromMilliseconds(100));
}
}
catch (Exception exc)
{
// Handle Errors here
}
}
public delegate void TargetFunction();
}
}