WPF DispatcherTimer throws exception after systems resumes work

323 views Asked by At

Let’s assume you create a DispatchTimer like this:

if (_updateTimer != null) return; 
_updateTimer = new DispatcherTimer(DispatcherPriority.Normal) {Interval = new TimeSpan(0, 0, 0, Settings.Default.UpdateIntervallSec)};
_updateTimer.Tick += UpdateTimerOnTick;
_updateTimer.Start();

Now your system goes to sleep or suspend from working. After the systems resumes work, a NullPointerException is throw by the code. To avoid this I register on an event SystemEvents.PowerModeChanged += SystemEventsOnPowerModeChanged;

With the following code:

private void SystemEventsOnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
    if (e.Mode == PowerModes.Suspend)
    {
        if (_updateTimer == null) return;
        _updateTimer.Tick -= UpdateTimerOnTick;
        _updateTimer.IsEnabled = false;
        _updateTimer.Stop();
    }
    if (e.Mode == PowerModes.Resume)
    {
        if (_updateTimer != null) return;
        _updateTimer = new DispatcherTimer(DispatcherPriority.Normal) {Interval = new TimeSpan(0, 0, 0, Settings.Default.UpdateIntervallSec)};
        _updateTimer.Tick += UpdateTimerOnTick;
        _updateTimer.Start();
    }
}

But this doesn’t solve the issue. The exception is called that the “UpdateTimerOnTick” method is null. Any good idea how to prevent this behavior?

1

There are 1 answers

0
Jehof On

You should set the variable _updateTimer to null when the system is suspended otherwise is your code on Resume not executed.

if (_updateTimer == null) return;
// your other code
_updateTimer = null;