我在c#中有一个计时器,每10 in执行一次线程:
private void setTimers(IntPtr paramA, List<int> paramB)
{
varTimer= new System.Timers.Timer();
varTimer.Elapsed += delegate { Check(paramA, paramB); };
varTimer.Interval = 10;
varTimer.Start();
}
职能如下:
private void Check(IntPtr paramA, List<int> paramB)
{
try
{
acquiredLock= false;
System.Threading.Monitor.TryEnter(syncThreadsC, ref acquiredLock);
if (acquiredLock)
{
// logic
}
else
{
return;
}
}
finally
{
if (acquiredLock)
System.Threading.Monitor.Exit(syncThreadsC);
}
}
我要求它每10毫秒发射一次,即使知道它不会是超精确的,当我进入和退出Check
时,如果我向Check
查询的话,我会得到这些数字
605 693 785 878 971 67 159
Check
的逻辑只需1到2ms。我想知道,因为我相信在c#中没有比这更精确的东西了,如果c++中有什么东西可以以更高的精度在每一个X毫秒启动一个定时器的话。如果是这样的话,我将在外部dll中这样做并调用它。这些数字对我来说太不合适了。
谢谢
发布于 2015-08-12 03:02:16
使用来自Raise event in high resolution interval/timer的校正计时器类,下面是一个高分辨率定时器的示例实现:
class Program
{
public void Main(string[] args)
{
uint timerId = SafeNativeMethods.timeSetEvent( 1, 1, HandleTimerTick, UIntPtr.Zero, 1 );
Console.ReadLine();
SafeNativeMethods.timeKillEvent( timerId );
}
public static void HandleTimerTick( uint id, uint msg, UIntPtr userCtx, UIntPtr uIntPtr, UIntPtr intPtr )
{
Console.WriteLine( "This is a bad idea on short timescales" );
}
}
public static class SafeNativeMethods
{
/// <summary>
/// A timer event handler
/// </summary>
/// <param name="id">Timer identifier, as returned by the timeSetEvent function.</param>
/// <param name="msg">Reserved</param>
/// <param name="userCtx">The value that was passed in to the userCtx value of the timeSetEvent function.</param>
/// <param name="dw1">Reserved</param>
/// <param name="dw2">Reserved</param>
public delegate void TimerEventHandler( UInt32 id, UInt32 msg, UIntPtr userCtx, UIntPtr dw1, UIntPtr dw2 );
/// <summary>
/// A multi media timer with millisecond precision
/// </summary>
/// <param name="msDelay">One event every msDelay milliseconds</param>
/// <param name="msResolution">Timer precision indication (lower value is more precise but resource unfriendly)</param>
/// <param name="handler">delegate to start</param>
/// <param name="userCtx">callBack data </param>
/// <param name="eventType">one event or multiple events</param>
/// <remarks>Dont forget to call timeKillEvent!</remarks>
/// <returns>0 on failure or any other value as a timer id to use for timeKillEvent</returns>
[DllImport( "winmm.dll", SetLastError = true, EntryPoint = "timeSetEvent" )]
public static extern UInt32 timeSetEvent( UInt32 msDelay, UInt32 msResolution, TimerEventHandler handler, UIntPtr userCtx, UInt32 eventType );
/// <summary>
/// The multi media timer stop function
/// </summary>
/// <param name="uTimerID">timer id from timeSetEvent</param>
/// <remarks>This function stops the timer</remarks>
[DllImport( "winmm.dll", SetLastError = true )]
public static extern void timeKillEvent( UInt32 uTimerID );
}
当您使用完timeKillEvent时,请确保干净地杀死您的计时器,并且不要在您的应用程序中使用大量这些计时器。它们是资源密集型的。
https://stackoverflow.com/questions/31954828
复制相似问题