Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event Handler in c# language

class Plane 
{
    public event EventHandler Land;

    protected void OnLand()
    {
        if ( null != Land ) 
        {
            Land( this, null );
        }
    }
}

it is event handler best practice to do instead:

EventHandler temp = Land;
if ( null != temp ) 
{
    temp( this, null );
}

Is that truly necessary? In what case could temp be different from Land?

like image 764
Pyadav Avatar asked Aug 20 '26 17:08

Pyadav


1 Answers

In the case of multi-threaded access, I believe. If you don't cache the reference, another thread can null it out after your guard but before you fire.

like image 82
Erik Dietrich Avatar answered Aug 22 '26 08:08

Erik Dietrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!