C# timeBeginPeriod在英特尔Comet Lake CPU上不工作(i5 10400H)

C# timeBeginPeriod在英特尔Comet Lake CPU上不工作(i5 10400H),c#,windows,winapi,intel,C#,Windows,Winapi,Intel,我的应用程序中有一些操作依赖于短计时器。使用下面的示例代码,我可以根据需要每5毫秒触发一次计时器 在Intel i5 10400H CPU上,观察到计时关闭,回调在约15毫秒(或15的倍数)后发生。使用ClockRes sysinternals工具表明,即使在以下代码中调用timeBeginPeriod(1)后运行,机器的系统计时器分辨率也为15ms 使用将分辨率设置为支持的最大值(0.5ms)不会改变示例代码的行为 从我所看到的情况来看,机器正在使用不变的TSC acpi计时器,强制它使用HP

我的应用程序中有一些操作依赖于短计时器。使用下面的示例代码,我可以根据需要每5毫秒触发一次计时器

在Intel i5 10400H CPU上,观察到计时关闭,回调在约15毫秒(或15的倍数)后发生。使用ClockRes sysinternals工具表明,即使在以下代码中调用
timeBeginPeriod(1)
后运行,机器的系统计时器分辨率也为15ms

使用将分辨率设置为支持的最大值(0.5ms)不会改变示例代码的行为

从我所看到的情况来看,机器正在使用不变的TSC acpi计时器,强制它使用HPET(使用
bcdedit/set useplatformclock true
并重新启动)并没有改变行为

我在CPU文档或勘误表中看不到任何可以解释这一点的内容

我不知道问题出在哪里,如果是我这边可以解决的问题,有什么想法吗

编辑:打开这个程序()会在预期的时候触发计时器队列,所以它是可解的

示例代码:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (new TimePeriod(1))
                RunTimer();
        }

        public static void RunTimer()
        {
            var completionEvent = new ManualResetEvent(false);
            var stopwatch = Stopwatch.StartNew();
            var i = 0;
            var previous = 0L;
            using var x = TimerQueue.Default.CreateTimer((s) =>
            {
                if (i > 100)
                    completionEvent.Set();
                i++;
                var now = stopwatch.ElapsedMilliseconds;
                var gap = now - previous;
                previous = now;
                Console.WriteLine($"Gap: {gap}ms");
            }, "", 10, 5);
            completionEvent.WaitOne();
        }
    }

    public class TimerQueueTimer : IDisposable
    {
        private TimerQueue MyQueue;
        private TimerCallback Callback;
        private object UserState;
        private IntPtr Handle;

        internal TimerQueueTimer(
            TimerQueue queue,
            TimerCallback cb,
            object state,
            uint dueTime,
            uint period,
            TimerQueueTimerFlags flags)
        {
            MyQueue = queue;
            Callback = cb;
            UserState = state;
            bool rslt = TQTimerWin32.CreateTimerQueueTimer(
                out Handle,
                MyQueue.Handle,
                TimerCallback,
                IntPtr.Zero,
                dueTime,
                period,
                flags);
            if (!rslt)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Error creating timer.");
            }
        }
        ~TimerQueueTimer()
        {
            Dispose(false);
        }
        public void Change(uint dueTime, uint period)
        {
            bool rslt = TQTimerWin32.ChangeTimerQueueTimer(MyQueue.Handle, ref Handle, dueTime, period);
            if (!rslt)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Error changing timer.");
            }
        }
        private void TimerCallback(IntPtr state, bool bExpired)
        {
            Callback.Invoke(UserState);
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        private IntPtr completionEventHandle = new IntPtr(-1);
        public void Dispose(WaitHandle completionEvent)
        {
            completionEventHandle = completionEvent.SafeWaitHandle.DangerousGetHandle();
            this.Dispose();
        }
        private bool disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                bool rslt = TQTimerWin32.DeleteTimerQueueTimer(MyQueue.Handle,
                    Handle, completionEventHandle);
                if (!rslt)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error(), "Error deleting timer.");
                }
                disposed = true;
            }
        }
    }

    public class TimerQueue : IDisposable
    {
        public IntPtr Handle { get; private set; }
        public static TimerQueue Default { get; private set; }
        static TimerQueue()
        {
            Default = new TimerQueue(IntPtr.Zero);
        }
        private TimerQueue(IntPtr handle)
        {
            Handle = handle;
        }
        public TimerQueue()
        {
            Handle = TQTimerWin32.CreateTimerQueue();
            if (Handle == IntPtr.Zero)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Error creating timer queue.");
            }
        }
        ~TimerQueue()
        {
            Dispose(false);
        }
        public TimerQueueTimer CreateTimer(
            TimerCallback callback,
            object state,
            uint dueTime,
            uint period)
        {
            return CreateTimer(callback, state, dueTime, period, TimerQueueTimerFlags.ExecuteInPersistentThread);
        }

        public TimerQueueTimer CreateTimer(
            TimerCallback callback,
            object state,
            uint dueTime,
            uint period,
            TimerQueueTimerFlags flags)
        {
            return new TimerQueueTimer(this, callback, state, dueTime, period, flags);
        }

        private IntPtr CompletionEventHandle = new IntPtr(-1);

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Dispose(WaitHandle completionEvent)
        {
            CompletionEventHandle = completionEvent.SafeWaitHandle.DangerousGetHandle();
            Dispose();
        }

        private bool Disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!Disposed)
            {
                if (Handle != IntPtr.Zero)
                {
                    bool rslt = TQTimerWin32.DeleteTimerQueueEx(Handle, CompletionEventHandle);
                    if (!rslt)
                    {
                        int err = Marshal.GetLastWin32Error();
                        throw new Win32Exception(err, "Error disposing timer queue");
                    }
                }
                Disposed = true;
            }
        }
    }

    public enum TimerQueueTimerFlags : uint
    {
        ExecuteDefault = 0x0000,
        ExecuteInTimerThread = 0x0020,
        ExecuteInIoThread = 0x0001,
        ExecuteInPersistentThread = 0x0080,
        ExecuteLongFunction = 0x0010,
        ExecuteOnlyOnce = 0x0008,
        TransferImpersonation = 0x0100,
    }

    public delegate void Win32WaitOrTimerCallback(
        IntPtr lpParam,
        [MarshalAs(UnmanagedType.U1)] bool bTimedOut);

    static public class TQTimerWin32
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        public extern static IntPtr CreateTimerQueue();

        [DllImport("kernel32.dll", SetLastError = true)]
        public extern static bool DeleteTimerQueue(IntPtr timerQueue);

        [DllImport("kernel32.dll", SetLastError = true)]
        public extern static bool DeleteTimerQueueEx(IntPtr timerQueue, IntPtr completionEvent);

        [DllImport("kernel32.dll", SetLastError = true)]
        public extern static bool CreateTimerQueueTimer(
            out IntPtr newTimer,
            IntPtr timerQueue,
            Win32WaitOrTimerCallback callback,
            IntPtr userState,
            uint dueTime,
            uint period,
            TimerQueueTimerFlags flags);

        [DllImport("kernel32.dll", SetLastError = true)]
        public extern static bool ChangeTimerQueueTimer(
            IntPtr timerQueue,
            ref IntPtr timer,
            uint dueTime,
            uint period);

        [DllImport("kernel32.dll", SetLastError = true)]
        public extern static bool DeleteTimerQueueTimer(
            IntPtr timerQueue,
            IntPtr timer,
            IntPtr completionEvent);
    }

    public sealed class TimePeriod : IDisposable
    {
        private const string WINMM = "winmm.dll";

        private static TIMECAPS timeCapabilities;

        private static int inTimePeriod;

        private readonly int period;

        private int disposed;

        [DllImport(WINMM, ExactSpelling = true)]
        private static extern int timeGetDevCaps(ref TIMECAPS ptc, int cbtc);

        [DllImport(WINMM, ExactSpelling = true)]
        private static extern int timeBeginPeriod(int uPeriod);

        [DllImport(WINMM, ExactSpelling = true)]
        private static extern int timeEndPeriod(int uPeriod);

        static TimePeriod()
        {
            int result = timeGetDevCaps(ref timeCapabilities, Marshal.SizeOf(typeof(TIMECAPS)));
            if (result != 0)
            {
                throw new InvalidOperationException("The request to get time capabilities was not completed because an unexpected error with code " + result + " occured.");
            }
        }

        internal TimePeriod(int period)
        {
            if (Interlocked.Increment(ref inTimePeriod) != 1)
            {
                Interlocked.Decrement(ref inTimePeriod);
                throw new NotSupportedException("The process is already within a time period. Nested time periods are not supported.");
            }

            if (period < timeCapabilities.wPeriodMin || period > timeCapabilities.wPeriodMax)
            {
                throw new ArgumentOutOfRangeException("period", "The request to begin a time period was not completed because the resolution specified is out of range.");
            }

            int result = timeBeginPeriod(period);
            if (result != 0)
            {
                throw new InvalidOperationException("The request to begin a time period was not completed because an unexpected error with code " + result + " occured.");
            }

            this.period = period;
        }

        internal static int MinimumPeriod
        {
            get
            {
                return timeCapabilities.wPeriodMin;
            }
        }

        internal static int MaximumPeriod
        {
            get
            {
                return timeCapabilities.wPeriodMax;
            }
        }

        internal int Period
        {
            get
            {
                if (this.disposed > 0)
                {
                    throw new ObjectDisposedException("The time period instance has been disposed.");
                }

                return this.period;
            }
        }

        public void Dispose()
        {
            if (Interlocked.Increment(ref this.disposed) == 1)
            {
                timeEndPeriod(this.period);
                Interlocked.Decrement(ref inTimePeriod);
            }
            else
            {
                Interlocked.Decrement(ref this.disposed);
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct TIMECAPS
        {
            internal int wPeriodMin;

            internal int wPeriodMax;
        }
    }
}

使用系统;
使用系统组件模型;
使用系统诊断;
使用System.Runtime.InteropServices;
使用系统线程;
名称空间控制台EAPP1
{
班级计划
{
静态void Main(字符串[]参数)
{
使用(新时间段(1))
运行计时器();
}
公共静态void RunTimer()
{
var completionEvent=新手动重置事件(假);
var stopwatch=stopwatch.StartNew();
var i=0;
var先前=0升;
使用var x=TimerQueue.Default.CreateTimer((s)=>
{
如果(i>100)
completionEvent.Set();
i++;
var now=stopwatch.elapsedmillisons;
var gap=现在-以前;
以前=现在;
WriteLine($“Gap:{Gap}ms”);
}, "", 10, 5);
completionEvent.WaitOne();
}
}
公共类计时器队列计时器:IDisposable
{
专用计时器队列MyQueue;
专用TimerCallback回调;
私有对象用户状态;
私有IntPtr句柄;
内部计时器队列计时器(
计时器队列,
TimerCallback cb,
对象状态,
二重唱时,
新时期,
TimerQueueTimerFlags标志)
{
MyQueue=队列;
回调=cb;
用户状态=状态;
bool rslt=TQTimerWin32.CreateTimerQueueTimer(
出格,
MyQueue.Handle,
时光倒流,
IntPtr.Zero,
决斗时间,
时期
旗帜);
如果(!rslt)
{
抛出新的Win32Exception(Marshal.GetLastWin32Error(),“创建计时器时出错”);
}
}
~TimerQueueTimer()
{
处置(虚假);
}
公共无效更改(uint dueTime、uint period)
{
bool rslt=TQTimerWin32.ChangeTimerQueueTimer(MyQueue.Handle,ref Handle,dueTime,period);
如果(!rslt)
{
抛出新的Win32Exception(Marshal.GetLastWin32Error(),“错误更改计时器”);
}
}
专用void TimerCallback(IntPtr状态,bool bExpired)
{
调用(UserState);
}
公共空间处置()
{
处置(真实);
总干事(本);
}
私有IntPtr completionEventHandle=new IntPtr(-1);
public void Dispose(WaitHandle completionEvent)
{
completionEventHandle=completionEvent.SafeWaitHandle.DangerousGetHandle();
这个。Dispose();
}
私有布尔=假;
受保护的虚拟void Dispose(bool disposing)
{
如果(!已处置)
{
bool rslt=TQTimerWin32.DeleteTimerQueueTimer(MyQueue.Handle,
句柄,completionEventHandle);
如果(!rslt)
{
抛出新的Win32Exception(Marshal.GetLastWin32Error(),“删除计时器时出错”);
}
这是真的;
}
}
}
公共类计时器队列:IDisposable
{
公共IntPtr句柄{get;private set;}
公共静态计时器队列默认值{get;private set;}
静态计时器队列()
{
默认值=新定时器队列(IntPtr.Zero);
}
专用计时器队列(IntPtr句柄)
{
把手=把手;
}
公共计时器队列()
{
Handle=TQTimerWin32.CreateTimerQueue();
if(Handle==IntPtr.Zero)
{
抛出新的Win32Exception(Marshal.GetLastWin32Error(),“创建计时器队列时出错”);
}
}
~TimerQueue()
{
处置(虚假);
}
公共计时器队列计时器创建计时器(
TimerCallback回调,
对象状态,
二重唱时,
(休止期)
{
返回CreateTimer(回调、状态、dueTime、时段、TimerQueueTimerFlags.ExecuteInputPersistentThread);
}
公共计时器队列计时器创建计时器(
TimerCallback回调,
对象状态,
二重唱时,
新时期,
TimerQueueTimerFlags标志)
{
返回新的TimerQueueTimer(this、回调、状态、dueTime、句点、标志);
}
私有IntPtr CompletionEventHandle=new IntPtr(-1);
公共空间处置()
{
处置(真实);
总干事(本);
}
public void Dispose(WaitHandle completionEvent)
{
有限公司