There is code sample in the chapter about events in the book about c#:
class CountDown
{
private uint _seconds;
public CountDown(uint seconds)
{
_seconds = seconds;
}
public void Start()
{
new Thread(() =>
{
uint n = _seconds;
while (n > 0u)
{
var tick = Tick; ///??????
if (tick != null)
tick(n);
Thread.Sleep(1000);
n--;
}
var finished = Finished; ///??????
if (finished != null)
finished();
}).Start();
}
}
public event Action<uint> Tick;
public event Action Finished;
What is the reason for creating local copy of event (tick and finished) and raising event via it? Is it common practice and have some sense? I tried but couldn’t get it from the book.
It avoids the possibility of
Tickbecoming null after the nullity check but before the call. If you had:… and the final listener was unsubscribed when you’d already got into “if” body, you’d get a
NullReferenceException.