TizzyT

MicroTimer 2018 -TizzyT

Aug 27th, 2018
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.87 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.InteropServices;
  4. using System.Threading;
  5.  
  6.     public class MicroTimer : IDisposable
  7.     {
  8.         [DllImport("winmm.dll")]
  9.         private static extern uint timeBeginPeriod(uint msec);
  10.  
  11.         private static readonly decimal TicksPerMillisecond = Stopwatch.Frequency / 1000M;
  12.         private decimal NextTime;
  13.         private Thread Iterator;
  14.         private int Ms;
  15.  
  16.         public event ElapsedEventHandler Elapsed;
  17.         public delegate void ElapsedEventHandler();
  18.         public decimal Interval { get; set; }
  19.  
  20.         static MicroTimer()
  21.         {
  22.             if (timeBeginPeriod(1) != 0) throw new Exception("High resolution timer not available.");
  23.         }
  24.  
  25.         public MicroTimer() => Interval = TicksPerMillisecond;
  26.  
  27.         public void Start(bool initial = false)
  28.         {
  29.             if (Iterator == null)
  30.             {
  31.                 NextTime = Stopwatch.GetTimestamp() + (initial ? 0 : Interval);
  32.                 Iterator = new Thread(() =>
  33.                 {
  34.                     while (true)
  35.                     {
  36.                         if ((Ms = (int)(Math.Floor((NextTime - Stopwatch.GetTimestamp()) / TicksPerMillisecond))) > 0) Thread.Sleep(Ms);
  37.                         while (Stopwatch.GetTimestamp() < NextTime) ;
  38.                         Elapsed?.Invoke();
  39.                         NextTime += Interval;
  40.                     }
  41.                 })
  42.                 {
  43.                     Priority = ThreadPriority.Highest,
  44.                     IsBackground = true
  45.                 };
  46.                 Iterator.Start();
  47.             }
  48.         }
  49.  
  50.         public void Stop()
  51.         {
  52.             if (Iterator != null)
  53.             {
  54.                 Iterator.Abort();
  55.                 Iterator = null;
  56.             }
  57.         }
  58.  
  59.         public void Dispose() => Iterator?.Abort();
  60.     }
Advertisement
Add Comment
Please, Sign In to add comment