gpt4 book ai didi

c# - 我可以让这个 TimerQueueTimer 类更高效吗?

转载 作者:行者123 更新时间:2023-11-30 18:42:10 26 4
gpt4 key购买 nike

using System;
using System.Threading;

internal class TimerQueueTimer : IDisposable
{
public TimerQueueTimer(int interval, int msBeforeFirstCall)
{
this.interval = interval;
this.msBeforeFirstCall = msBeforeFirstCall;
this.callback = this.ticked;
this.isTheFirstTick = true;
this.isStopped = true;
}

public event EventHandler Ticked;

public void Start()
{
if (!this.isStopped)
{
return;
}

this.isTheFirstTick = true;
this.isStopped = false;
Computer.ChangeTimerResolutionTo(1);
NativeMethods.CreateTimerQueueTimer(
out this.handle,
IntPtr.Zero,
this.callback,
IntPtr.Zero,
(uint)this.msBeforeFirstCall,
(uint)this.interval,
CallbackExecution.ExecuteInTimerThread);
}

public void Stop()
{
if (this.isStopped)
{
return;
}

NativeMethods.DeleteTimerQueueTimer(
IntPtr.Zero,
this.handle,
IntPtr.Zero);
Computer.ClearTimerResolutionChangeTo(1);
this.isStopped = true;
}

public void Dispose()
{
this.Stop();
}

private void ticked(IntPtr parameterPointer, bool timerOrWaitFired)
{
if (this.isStopped)
{
return;
}

if (this.isTheFirstTick)
{
Thread.CurrentThread.Priority = ThreadPriority.Highest;
}

this.isTheFirstTick = false;
var ticked = this.Ticked;
if (ticked != null)
{
ticked(this, EventArgs.Empty);
}
}

private IntPtr handle;
private volatile bool isStopped;
private volatile bool isTheFirstTick;
private readonly WaitOrTimerDelegate callback;
private readonly int interval;
private readonly int msBeforeFirstCall;
}

(注意:Computer.ChangeTimerResolutionTo()Computer.ClearTimerResolutionChangeTo() 调用 timeBeginPeriodtimeEndPeriod,分别。)

问题:

  1. 回调在计时器的线程中运行,而不是在 ThreadPool 线程中运行。只要回调函数很快就没问题,对吧?
  2. 将回调线程(以及计时器线程)的优先级设置为“最高”对性能有何影响?
  3. 如果 tickCount % interval == 0,将定时器间隔设置为 1ms 并计数滴答,提高 Ticked 是否更好?间隔时间越短的计时器越准确吗?
  4. 与类似创建的 timeSetEvent 计时器相比,这是否有任何原因可能不够准确和/或精确?

我问的原因是因为我们遇到了定时器回调的问题,当系统负载很重时,定时器回调偶尔会延迟大约 50 毫秒。与我们之前使用 timeSetEvent 时相比,感觉这种情况发生的频率降低了——尽管这可能只是一种错觉。我知道 Windows 不是确定性的,所以我能做的只有这么多。但是,我想确保我已尽我所能使它尽可能成为高优先级。还有什么我可以做的吗?

最佳答案

我使用优先级队列来解决这个问题:队列的每个元素都包含回调地址(定时器例程)、指向回调参数的指针以及 future 触发回调的时间。

'时间'是优先级,这里的逻辑是有可能从另一个线程唤醒定时器线程。当另一个线程将回调添加到队列时,计时器线程将被唤醒,它会查找优先级队列的顶部元素,计算当前时间与存储在队列中的“时间”之间的差异,然后休眠直到计算超时。

当计时器线程被超时唤醒时,它会从调用回调的线程池中启动新线程。

我有一个计时器队列实现 here ,它没有经过充分测试,但您可以看看它是否有帮助。

关于c# - 我可以让这个 TimerQueueTimer 类更高效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5959484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com