Reputation: 613
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?
Upvotes: 0
Views: 297
Reputation: 35564
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;
Upvotes: 0