Safely firing an event

This came up on an internal alias, and I thought I should spread it around.

If you’re going to fire an event, you may have code like this:

 

      void F()

      {

            if (SomeEvent != null)

            {

                  SomeEvent();

            }

      }

 

There’s a race condition here. If another thread removes the last handler between the if() and the call, then it’ll crash.

The safe way is to use the copy-and-test pattern:

      void FireSomeEvent()

      {

            D temp = SomeEvent;

            if (temp != null)

            {

                  temp();

            }

      }