今天在一台机器上发生的 NullReference 异常是否有任何解释。我无法在我的计算机上复制它......
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
}
}
基于 Mark Hall 和 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
}
}