System.Timers.Timer 每秒最多只能提供 64 帧 [英] System.Timers.Timer only gives maximum 64 frames per second
问题描述
我有一个应用程序,它使用 System.Timers.Timer 对象来引发由主表单处理的事件 (Windows 窗体、C#).我的问题是,无论我将 .Interval 设置多短(甚至设置为 1 毫秒),我每秒最多可以获得 64 次.
I have an application that uses a System.Timers.Timer object to raise events that are processed by the main form (Windows Forms, C#). My problem is that no matter how short I set the .Interval (even to 1 ms) I get a max of 64 times per second.
我知道 Forms 计时器有 55 毫秒的准确度限制,但这是 System.Timer 变体,而不是 Forms 变体.
I know the Forms timer has a 55 ms accuracy limit, but this is the System.Timer variant, not the Forms one.
该应用程序占用 1% 的 CPU,因此它绝对不受 CPU 限制.所以它所做的就是:
The application sits a 1% CPU, so it's definitely not CPU-bound. So all it's doing is:
- 将计时器设置为 1&nsp;ms
- 当事件触发时,增加一个 _Count 变量
- 再次将其设置为 1&nsp;ms 并重复
_Count 每秒最多递增 64 次,即使没有其他工作要做.
_Count gets incremented a maximum of 64 times a second even when there's no other work to do.
这是一个回放"应用程序,它必须复制进来的数据包,它们之间只有 1-2 毫秒的延迟,所以我需要一些可以每秒可靠地触发 1000 次左右的东西(尽管我会解决如果我受 CPU 限制,则为 100,我不是).
This is an "playback" application that has to replicate packets coming in with as little as 1-2 ms delay between them, so I need something that can reliably fire 1000 times a second or so (though I'd settle for 100 if I was CPU bound, I'm not).
有什么想法吗?
推荐答案
尝试 多媒体计时器 - 它们为硬件平台提供尽可能高的准确性.这些计时器以比其他计时器服务更高的分辨率安排事件.
Try Multimedia Timers - they provide greatest accuracy possible for the hardware platform. These timers schedule events at a higher resolution than other timer services.
您将需要以下 Win API 函数来设置计时器分辨率、启动和停止计时器:
You will need following Win API functions to set timer resolution, start and stop timer:
[DllImport("winmm.dll")]
private static extern int timeGetDevCaps(ref TimerCaps caps, int sizeOfTimerCaps);
[DllImport("winmm.dll")]
private static extern int timeSetEvent(int delay, int resolution, TimeProc proc, int user, int mode);
[DllImport("winmm.dll")]
private static extern int timeKillEvent(int id);
您还需要回调委托:
delegate void TimeProc(int id, int msg, int user, int param1, int param2);
和定时器功能结构
[StructLayout(LayoutKind.Sequential)]
public struct TimerCaps
{
public int periodMin;
public int periodMax;
}
用法:
TimerCaps caps = new TimerCaps();
// provides min and max period
timeGetDevCaps(ref caps, Marshal.SizeOf(caps));
int period = 1;
int resolution = 1;
int mode = 0; // 0 for periodic, 1 for single event
timeSetEvent(period, resolution, new TimeProc(TimerCallback), 0, mode);
和回调:
void TimerCallback(int id, int msg, int user, int param1, int param2)
{
// occurs every 1 ms
}
这篇关于System.Timers.Timer 每秒最多只能提供 64 帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!