MTimer.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace SIASUN.Autopilot.Device.Common
  8. {
  9. /// <summary>
  10. /// 基于系统性能计数器的定时器,计数单位是1微秒=1/1000毫秒
  11. /// 注意:该定时器会独占一个CPU核心,尝试定时器与主程序运行在同一核心将导致程序失去响应
  12. /// </summary>
  13. public class MTimer
  14. {
  15. /// <summary>
  16. /// 获取当前系统性能计数
  17. /// </summary>
  18. /// <param name="lpPerformanceCount"></param>
  19. /// <returns></returns>
  20. [DllImport("Kernel32.dll")]
  21. private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
  22. /// <summary>
  23. /// 获取当前系统性能频率
  24. /// </summary>
  25. /// <param name="lpFrequency"></param>
  26. /// <returns></returns>
  27. [DllImport("Kernel32.dll")]
  28. private static extern bool QueryPerformanceFrequency(out long lpFrequency);
  29. /// <summary>
  30. /// 指定某一特定线程运行在指定的CPU核心
  31. /// </summary>
  32. /// <param name="hThread"></param>
  33. /// <param name="dwThreadAffinityMask"></param>
  34. /// <returns></returns>
  35. [DllImport("kernel32.dll")]
  36. static extern UIntPtr SetThreadAffinityMask(IntPtr hThread, UIntPtr dwThreadAffinityMask);
  37. /// <summary>
  38. /// 获取当前线程的Handler
  39. /// </summary>
  40. /// <returns></returns>
  41. [DllImport("kernel32.dll")]
  42. static extern IntPtr GetCurrentThread();
  43. /// <summary>
  44. /// 是否销毁定时器
  45. /// </summary>
  46. private bool _Dispose = false;
  47. /// <summary>
  48. /// 是否正在运行定时器
  49. /// </summary>
  50. private bool _BRunTimer = false;
  51. /// <summary>
  52. /// 首次启动延时(微秒)
  53. /// </summary>
  54. private uint _Delay = 0;
  55. /// <summary>
  56. /// 定时器周期(微秒)
  57. /// </summary>
  58. private long _Period = 10;
  59. /// <summary>
  60. /// 定时器运行时独占的CPU核心索引序号
  61. /// </summary>
  62. private byte _CpuIndex = 0;
  63. /// <summary>
  64. /// 系统性能计数频率(每秒)
  65. /// </summary>
  66. private long _Freq = 0;
  67. /// <summary>
  68. /// 系统性能计数频率(每微秒)
  69. /// </summary>
  70. private long _Freqmms = 0;
  71. /// <summary>
  72. /// 回调函数定义
  73. /// </summary>
  74. private OnTickHandle Tick;
  75. /// <summary>
  76. /// 根据CPU的索引序号获取CPU的标识序号
  77. /// </summary>
  78. /// <param name="idx"></param>
  79. /// <returns></returns>
  80. private ulong GetCpuID(int idx)
  81. {
  82. ulong cpuid = 0;
  83. if (idx < 0 || idx >= System.Environment.ProcessorCount)
  84. {
  85. idx = 0;
  86. }
  87. cpuid |= 1UL << idx;
  88. return cpuid;
  89. }
  90. /// <summary>
  91. /// 定时器构造函数
  92. /// </summary>
  93. /// <param name="delay">首次启动定时器延时时间(微秒)</param>
  94. /// <param name="period">定时器触发的周期(微秒)</param>
  95. /// <param name="cpuIndex">指定定时器线程独占的CPU核心索引,必须>0,不允许为定时器分配0#CPU</param>
  96. /// <param name="tick">定时器触发时的回调函数</param>
  97. public MTimer(uint delay, uint period, byte cpuIndex, OnTickHandle tick)
  98. {
  99. Tick = tick;
  100. _Delay = delay;
  101. _Period = period;
  102. _CpuIndex = cpuIndex;
  103. long freq = 0;
  104. QueryPerformanceFrequency(out freq);
  105. if (freq > 0)
  106. {
  107. _Freq = freq;
  108. _Freqmms = freq / 1000000;//每微秒性能计数器跳跃次数
  109. }
  110. else
  111. {
  112. throw new Exception("初始化定时器失败");
  113. }
  114. if (_CpuIndex == 0)
  115. {
  116. throw new Exception("定时器不允许被分配到0#CPU");
  117. }
  118. if (_CpuIndex >= System.Environment.ProcessorCount)
  119. {
  120. throw new Exception("为定时器分配了超出索引的CPU");
  121. }
  122. }
  123. private System.Threading.Thread _threadRumTimer;
  124. /// <summary>
  125. /// 开启定时器
  126. /// </summary>
  127. public void Open()
  128. {
  129. if (Tick != null)
  130. {
  131. _threadRumTimer = new System.Threading.Thread(new System.Threading.ThreadStart(RunTimer));
  132. _threadRumTimer.Start();
  133. }
  134. }
  135. /// <summary>
  136. /// 运行定时器
  137. /// </summary>
  138. private void RunTimer()
  139. {
  140. UIntPtr up = UIntPtr.Zero;
  141. if (_CpuIndex != 0)
  142. up = SetThreadAffinityMask(GetCurrentThread(), new UIntPtr(GetCpuID(_CpuIndex)));
  143. if (up == UIntPtr.Zero)
  144. {
  145. throw new Exception("为定时器分配CPU核心时失败");
  146. }
  147. long q1, q2;
  148. QueryPerformanceCounter(out q1);
  149. QueryPerformanceCounter(out q2);
  150. if (_Delay > 0)
  151. {
  152. while (q2 < q1 + _Delay * _Freqmms)
  153. {
  154. QueryPerformanceCounter(out q2);
  155. }
  156. }
  157. QueryPerformanceCounter(out q1);
  158. QueryPerformanceCounter(out q2);
  159. while (!_Dispose)
  160. {
  161. _BRunTimer = true;
  162. QueryPerformanceCounter(out q2);
  163. if (q2 > q1 + _Freqmms * _Period)
  164. {
  165. //***********回调***********//
  166. if (!_Dispose)
  167. Tick(this, (q2 - q1) / (_Freqmms * _Period), (q2 - q1) / _Freqmms);
  168. q1 = q2;
  169. //System.Windows.Forms.Application.DoEvents();//会导致线程等待windows消息循环,时间损失15ms以上
  170. }
  171. _BRunTimer = false;
  172. }
  173. }
  174. /// <summary>
  175. /// 销毁当前定时器所占用的资源
  176. /// </summary>
  177. public void Dispose()
  178. {
  179. _Dispose = true;
  180. while (_BRunTimer)
  181. System.Windows.Forms.Application.DoEvents();//在工作未完成之前,允许处理消息队列,防止调用者挂起
  182. if (_threadRumTimer != null)
  183. _threadRumTimer.Abort();
  184. }
  185. /// <summary>
  186. /// 定时器事件的委托定义
  187. /// </summary>
  188. /// <param name="sender">事件的发起者,即定时器对象</param>
  189. /// <param name="JumpPeriod">上次调用和本次调用跳跃的周期数</param>
  190. /// <param name="interval">上次调用和本次调用之间的间隔时间(微秒)</param>
  191. public delegate void OnTickHandle(object sender, long JumpPeriod, long interval);
  192. }
  193. }