C#: In what cases should you null out references?

后端 未结 3 1015
情话喂你
情话喂你 2021-02-14 05:39

The CLR Profiler can also reveal which methods allocate more storage than you expected, and can uncover cases where you inadvertently keep references to useless o

3条回答
  •  梦毁少年i
    2021-02-14 06:25

    It's important if you have long lived objects (like the cache example in your quote) holding references to short lived objects (like the cache items). Other examples of long lived objects could be singleton objects, the Main Form instance in a Windows Forms application, the Application instance of a ASP.NET application etc.

    I would like to add a another common pitfull: short lived objects subscribing to events published by long lived objects. As the event publisher holds a reference to all subscribers, the subscribers (like e. g. ASP.NET page or control instances that are needed only for milliseconds) won't be collected if you do not unsubscribe.

提交回复
热议问题