Why and How to avoid Event Handler memory leaks?

前端 未结 4 1687
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 16:10

I just came to realize, by reading some questions and answers on StackOverflow, that adding event handlers using += in C# (or i guess, other .net languages) can

4条回答
  •  天涯浪人
    2020-11-22 16:46

    An event is really a linked list of event handlers

    When you do += new EventHandler on the event it doesn’t really matter if this particular function has been added as a listener before, it will get added once per +=.

    When the event is raised it go through the linked list, item by item and call all the methods (event handlers) added to this list, this is why the event handlers are still called even when the pages are no longer running as long as they are alive (rooted), and they will be alive as long as they are hooked up. So they will get called until the eventhandler is unhooked with a -= new EventHandler.

    See Here

    and MSDN HERE

提交回复
热议问题