开发者

DispatcherTimer in Silverlight 4 losing time - what is more accurate?

开发者 https://www.devze.com 2023-01-11 01:30 出处:网络
I have a poker blind timer Silverlight app that is losing time (after running for 1 hour 40 minutes it had lost 3 minutes).

I have a poker blind timer Silverlight app that is losing time (after running for 1 hour 40 minutes it had lost 3 minutes).

I use a DispatcherTimer timer in my Tournament class and on every tick I raise an event which the UI subscribes to to update the screen (with a DataBound Textblock). I then do checks to see if the blind is over or if there is 60 seconds left etc:

private DispatcherTimer timerBlind;


        if (timerBlind == null)
        {
            timerBlind = new DispatcherTimer();
            timerBlind.Interval = TimeSpan.FromSeconds(1);
            timerBlind.Tick += new EventHandler(Timer_Tick);
        }

  void Timer_Tick(object sender, EventArgs e)
    {
        //check if this would be the end of the blind or other key events
        OnTimerTick(new EventArgs());

        BlindSet.TotalTimeRunning = BlindSet.TotalTimeRunning.Add(TimeSpan.FromSeconds(1));

        if (IsTimerBlindRunning)
        {
            BlindSet.TimeLeftInCurrentBlind = BlindSet.TimeLeftInCurrentBlind.Add(TimeSpan.FromSeconds(-1));

            if (BlindSet.Ti开发者_如何学CmeLeftInCurrentBlind.TotalSeconds == 0)
            {
                //advance the level = blinds have gone up
                blindset.EndOfBlindGoToNextLevel();
            }
        }
    }

So, how do I make it more accurate? Thanks for any advice...


Don't use:

BlindSet.TotalTimeRunning = BlindSet.TotalTimeRunning.Add(TimeSpan.FromSeconds(1));

You are getting cumulative errors because Timers rarely fire exactly on cue.

Instead, store the time from the start of the blind (_startTime) and make a property:

TimeSpan TotalRunningTime{
    get{
        return DateTime.UtcNow-_startTime;
    }
}

Apply this approach to TimeLeftInCurrentBlind too.

0

精彩评论

暂无评论...
验证码 换一张
取 消