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
- {
- [DllImport("winmm.dll")]
- private static extern uint timeBeginPeriod(uint msec);
- private static readonly decimal TicksPerMillisecond = Stopwatch.Frequency / 1000M;
- private decimal NextTime;
- private Thread Iterator;
- private int Ms;
- public event ElapsedEventHandler Elapsed;
- public delegate void ElapsedEventHandler();
- public decimal Interval { get; set; }
- static MicroTimer()
- {
- if (timeBeginPeriod(1) != 0) throw new Exception("High resolution timer not available.");
- }
- public MicroTimer() => Interval = TicksPerMillisecond;
- public void Start(bool initial = false)
- {
- if (Iterator == null)
- {
- NextTime = Stopwatch.GetTimestamp() + (initial ? 0 : Interval);
- Iterator = new Thread(() =>
- {
- while (true)
- {
- if ((Ms = (int)(Math.Floor((NextTime - Stopwatch.GetTimestamp()) / TicksPerMillisecond))) > 0) Thread.Sleep(Ms);
- while (Stopwatch.GetTimestamp() < NextTime) ;
- Elapsed?.Invoke();
- NextTime += Interval;
- }
- })
- {
- Priority = ThreadPriority.Highest,
- IsBackground = true
- };
- Iterator.Start();
- }
- }
- public void Stop()
- {
- if (Iterator != null)
- {
- Iterator.Abort();
- Iterator = null;
- }
- }
- public void Dispose() => Iterator?.Abort();
- }
Advertisement
Add Comment
Please, Sign In to add comment