我们假设你创建一个像这样的DispatchTimer:
if (_updateTimer != null) return; _updateTimer = new DispatcherTimer(DispatcherPriority.Normal) {Interval = new TimeSpan(0, 0, 0, Settings.Default.UpdateIntervallSec)}; _updateTimer.Tick += UpdateTimerOnTick; _updateTimer.Start();
现在您的系统进入睡眠状态或暂停工作状态。系统恢复工作后,代码抛出NullPointerException。为避免这种情况,我在事件SystemEvents.PowerModeChanged += SystemEventsOnPowerModeChanged;
使用以下代码:
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(); } }
但这并没有解决问题。称为“UpdateTimerOnTick”方法为null的异常。有什么好主意如何防止这种行为?
答案 0 :(得分:0)
您应该在系统暂停时将变量_updateTimer
设置为null
,否则您的代码将在Resume未执行。
if (_updateTimer == null) return;
// your other code
_updateTimer = null;