C# Events and Thread Safety

前端 未结 15 1328
甜味超标
甜味超标 2020-11-22 06:00

UPDATE

As of C# 6, the answer to this question is:

SomeEvent?.Invoke(this, e);

I frequently hear/read the fo

15条回答
  •  萌比男神i
    2020-11-22 06:11

    According to Jeffrey Richter in the book CLR via C#, the correct method is:

    // Copy a reference to the delegate field now into a temporary field for thread safety
    EventHandler temp =
    Interlocked.CompareExchange(ref NewMail, null, null);
    // If any methods registered interest with our event, notify them
    if (temp != null) temp(this, e);
    

    Because it forces a reference copy. For more information, see his Event section in the book.

提交回复
热议问题