0

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?

sandkasten
  • 603
  • 1
  • 8
  • 21
  • Please add the complete message and stacktrace of the exception you are getting – Jehof Sep 10 '13 at 06:43
  • No stacktrace or further message availble. If the debuger is connected, erverything works fine. Otherwise only the short windows message is shown. – sandkasten Sep 10 '13 at 07:39

1 Answers1

0

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;
Jehof
  • 34,674
  • 10
  • 123
  • 155