当前位置: 首页 > 编程语言 > C#

如何将定时器分辨率从C#设置为1毫秒?Share

时间:2023-04-10 18:26:23 C#

如何在C#中将计时器分辨率设置为1毫秒?我使用过这个工具,发现我的WindowsServer2008R2Standard的分辨率为15毫秒,而Windows8的分辨率为1毫秒。我宁愿在WindowsServer2008R2上将计时器分辨率设置为1毫秒,因为我运行的是低延迟软件。我找到了这篇msdn文章,但它没有解释如何从C#程序更改计时器分辨率。我怎么办?你可以试试这个:publicstaticclassWinApi{///TimeBeginPeriod().有关详细信息,请参阅WindowsAPI文档。[System.Diagnostics.CodeAnalysis.SuppressMessage(“Microsoft.Interoperability”,“CA1401:PInvokesShouldNotBeVisible”),System.Diagnostics.CodeAnalysis.SuppressMessage(“Microsoft.Security”,“CA2118:ReviewSuppressUnmanagedCodeSecurityUsage”),SuppressUnmanagedCodeSecurity][DllImport(“winmm.dll",EntryPoint="timeBeginPeriod",SetLastError=true)]publicstaticexternuintTimeBeginPeriod(uintuMilliseconds);///时间结束时间()。有关详细信息,请参阅WindowsAPI文档。[System.Diagnostics.CodeAnalysis.SuppressMessage(“Microsoft.Interoperability”,“CA1401:PInvokesShouldNotBeVisible”),System.Diagnostics.CodeAnalysis.SuppressMessage(“Microsoft.Security”,“CA2118:ReviewSuppressUnmanagedCodeSecurityUsage”),SuppressUnmanagedCodeSecurity][DllImport(“winmm.dll",EntryPoint="timeEndPeriod",SetLastError=true)]publicstaticexternuintTimeEndPeriod(uintuMilliseconds);}并像这样使用它:WinApi.TimeBeginPeriod(1);并返回原来的类型:WinApi.TimeEndPeriod(1);更好的代码实际上是:使用系统;使用System.Runtime.InteropServices;使用系统线程;内部密封类TimePeriod:IDisposable{privateconststringWINMM="winmm.dll";私有静态TIMECAPStimeCapabilities;私有静态intinTimePeriod;私人只读期间;私有int处置;[DllImport(WINMM,ExactSpelling=true)]privatestaticexterninttimeGetDevCaps(refTIMECAPSptc,intcbtc);[DllImport(WINMM,ExactSpelling=true)]privatestaticexterninttimeBeginPeriod(intuPeriod);[DllImport(WINMM,ExactSpelling=true)]privatestaticexterninttimeEndPeriod(intuPeriod);staticTimePeriod(){intresult=timeGetDevCaps(reftimeCapabilities,Marshal.SizeOf(typeof(TIMECAPS)));if(result!=0){thrownewInvalidOperationException("获取时间功能的请求未完成,因为未完成代码“+结果+”发生预期错误。”);}}内部TimePeriod(intperiod){if(Interlocked.Increment(refinTimePeriod)!=1){Interlocked.Decrement(refinTimePeriod);抛出新的NotSupportedException(“该进程已经在一个时间段内。不支持嵌套时间段。");}if(periodtimeCapabilities.wPeriodMax){thrownewArgumentOutOfRangeException("period","开始一个时间段的请求未完成,因为解析指定超出范围。”);}intresult=timeBeginPeriod(period);if(result!=0){thrownewInvalidOperationException(“开始时间段的请求未完成,因为代码出现意外错误”+result+"发生了。");}this.period=period;}internalstaticintMinimumPeriod{get{returntimeCapabilities.wPeriodMin;}}internalstaticintMaximumPeriod{get{returntimeCapabilities.wPeriodMax;}}internalintPeriod{get{if(this.disposed>0){thrownewObjectDisposedException("时间段实例已被释放。");}返回this.period;}}publicvoidDispose(){if(Interlocked.Increment(refthis.disposed)==1){timeEndPeriod(this.period);Interlocked.Decrement(refinTimePeriod);}else{Interlocked.Decrement(refthis.disposed);}}[StructLayout(LayoutKind.Sequential)]privatestructTIMECAPS{内部intwPeriodMin;内部intwPeriodMax;}}使用:以上是C#学习教程:C#如何设置定时器分辨率为1ms?分享的所有内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——using(newTimePeriod(1)){////...}本文收藏来自网络,不代表Stand,如涉及侵权,请点击维权联系管理员删除,如需转载请注明出处: