Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- using System.Threading;
- public class MicroTimer : IDisposable
- {
- // Windows Multi-Media library to request a higher resolution period for the timer.
- [DllImport("winmm.dll")]
- private static extern uint timeBeginPeriod(uint msec);
- // Computes how many ticks are in each millisecond.
- private static readonly decimal TicksPerMillisecond = Stopwatch.Frequency / 1000M;
- // Stores the next time the Timer should elapse at.
- private decimal NextTime;
- // The thread which to keep track of timing, as to not block.
- private Thread Iterator;
- // Stores the number of millisecond the next iteration will wait for.
- private int Ms;
- // The Elapsed event, fired when the Timer has reached or exceeded its NextTIme value.
- public event ElapsedEventHandler Elapsed;
- public delegate void ElapsedEventHandler();
- // The number of ticks each iteration will take.
- public decimal Interval { get; set; }
- // Static constructor to request high resolution from Operation System. Throws if fails.
- static MicroTimer()
- {
- if (timeBeginPeriod(1) != 0) throw new Exception("High resolution timer not available.");
- }
- // Default constructor which initializes the interval to 1 second.
- public MicroTimer() => Interval = TicksPerMillisecond;
- // Starts the Timer if it hasn't started already.
- public void Start(bool initial = false)
- {
- if (Iterator == null)
- {
- // Sets the NextTime to the current time with the addition of the Interval (ticks per iteration) if specified.
- NextTime = Stopwatch.GetTimestamp() + (initial ? 0 : Interval);
- // Initializes a new thread
- Iterator = new Thread(() =>
- {
- // Infinite loop to track time.
- while (true)
- {
- // Assigns Ms to how much time in millisecond until NextTime is reached and if that evaluation is greater than 0. If it is, sleep for that amount in milliseconds.
- if ((Ms = (int)(Math.Floor((NextTime - Stopwatch.GetTimestamp()) / TicksPerMillisecond))) > 0) Thread.Sleep(Ms);
- // Poll with the remaining left over Ticks (sub millisecond precision).
- while (Stopwatch.GetTimestamp() < NextTime) ;
- // Fire Elapsed Event if not null.
- Elapsed?.Invoke();
- // Set the NextTime to the next iteration.
- NextTime += Interval;
- }
- })
- {
- Priority = ThreadPriority.Highest, // Have this thread at a high priority.
- IsBackground = true // Prevent thread from still running after application has closed.
- };
- Iterator.Start(); // Starts the Thread.
- }
- }
- // Stops the Thread and nulls it.
- public void Stop()
- {
- if (Iterator != null)
- {
- Iterator.Abort();
- Iterator = null;
- }
- }
- // Disposes this object (implemented to the using statement can be used).
- public void Dispose() => Iterator?.Abort();
- }
Add Comment
Please, Sign In to add comment