The C# events implementation (articles vs reflector)

前端 未结 3 985
自闭症患者
自闭症患者 2021-02-10 09:12

public class EventsType { public event EventHandler> NewEvent;

    public void SmthHappened(string data)
    {
        MyEventArgs even         


        
                      
相关标签:
3条回答
  • 2021-02-10 09:34

    The answer to this question very much depends on the version you're using. It has been refined a lot over the years. See http://blogs.msdn.com/b/cburrows/archive/2010/03/05/events-get-a-little-overhaul-in-c-4-part-i-locks.aspx

    0 讨论(0)
  • 2021-02-10 09:39

    Yup: C# 4 has made some changes in this area, basically. It makes it thread-safe without locking. That's not the only change - it also changes how references to field-like events within the class are resolved: += and -= now go through the "add" and "remove" bits rather than working directly with the backing field.

    Note that this change affects code compiled with the C# 4 compiler even against older frameworks; there are also changes to locking which only affect code compiled against .NET 4, as it uses a new method (Monitor.TryEnter(object, out bool)).

    0 讨论(0)
  • 2021-02-10 09:44

    What you are expecting is a simple non thread safe implementation. The field like event syntax always provide thread-safe syntax (hence the reflector version). Refer this artcile for understanding events & how they get implemented.

    0 讨论(0)
提交回复
热议问题