当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Trying to update interval for DispatcherTimer, not always working

问题描述:

I am trying to make a Snake game. And what I want to happen is that each time the snake eats a piece of food it moves quicker.

I want to do this by making the timer tick faster.

I start the timer at an interval time of:

gltimer.Interval = new TimeSpan(20000)

And update it with:

public void updateTimer(object sender, EventArgs e)

{

long nrTicks = gltimer.Interval.Ticks;

nrTicks = (long)(nrTicks * 0.95);

gltimer.Interval = new TimeSpan(nrTicks);

}

But when I run my game the speed stays the same until I reach the 14th snack and then it suddenly changes. I already figured out that the nrTicks then drops below 10000.

My question is why the Interval doesn't update for the intermediate values?

网友答案:

The DispatcherTimer is not designed to execute an action at precise intervals.

While it dispatches the action at the exact interval, the dispatched actions will get executed, when the GUI thread in your case the wpf application loop decides to do so.

You setting the interval to 20.000 ticks results in an interval of 20.000*100ns = 2.000.000ns = 2ms. A wpf application has a resolution of around 10ms at best.

Look at those posts:

  • WPF Timer problem... Cannot get correct millisecond tick
  • WPF Dispatchertimer delayed reaction / freeze
分享给朋友:
您可能感兴趣的文章:
随机阅读: