Is there any explanation to NullReference exception, that occured at one machine today. I cannot reproduce it at my computer….
class Test
{
Timer timer_;
public void Init()
{
timer_ = new Timer();
timer_.Interval = 10000;
timer_.Tick += OnTimerTick;
timer_.Start();
}
private void OnTimerTick(object sender, EventArgs e)
{
timer_.Stop();
timer_ = null; <--- Null Ref occurs
}
}
Solution based on awesome advices of Mark Hall and Rich Okelly
private void OnTimerTick(object sender, EventArgs e)
{
var localTimer = Interlocked.Exchange(ref timer_, null);
if (localTimer != null)
{
localTimer.Stop();
localTimer.Tick -= OnTimerTick;
localTimer.Dispose();
// doing staff
}
}
I think the null reference exception actually occurs the line above: at
timer_.Stop().What happened was the Tick event was raised and another scheduled, the timer was stopped and set to null as a result of the first Tick event. The second Tick event then tries to call Stop on the Timer, which is now null.
You can use the Interlocked methods to work around this: