Handles vs. AddHandler

前端 未结 7 487
花落未央
花落未央 2021-01-15 18:53

Is there an advantage to dynamically attaching/detaching event handlers?

Would manually detaching handlers help ensure that there isn\'t a reference remaining to a d

7条回答
  •  情歌与酒
    2021-01-15 19:30

    Declaring a field as WithEvents will cause the compiler to automatically generate a property with that name. The getter returns the value of a backing field. The setter is a little more complicated. It first checks whether the backing field already has the correct value. If so, it exits. Otherwise, if the backing field is non-null, it issues "RemoveHandler" requests for all its events to the object identified by the backing field. Next, regardless of whether the backing field was non-null, it sets it equal to the requested value. Finally, if the new value is non-null, whether the old one was or not, the property issues "AddHandler" requests for all its events to the object identified by the new value.

    Provided that one sets all of an object's WithEvents members to Nothing before abandoning it, and avoids manipulating WithEvents members in multiple threads, the auto-generated event code will not leak.

提交回复
热议问题