开发者

Memory leak with ContextMenuStrip

开发者 https://www.devze.com 2022-12-30 02:16 出处:网络
I\'m creating a lot of custom controls and adding them to a FlowLayoutPanel. There is also a ContextMenuStrip created and populated at design time.

I'm creating a lot of custom controls and adding them to a FlowLayoutPanel. There is also a ContextMenuStrip created and populated at design time.

Every time a control is added to the panel it h开发者_开发知识库as its ContextMenuStrip property assigned to this menu, so that all controls "share" the same menu. But I noticed when the controls are removed from the panel and disposed of, the memory in use in Task Manager doesn't drop. It rises around 50kB every time a control is created and added to the layout panel.

I downloaded the trial of .NET Memory Profiler and it showed there were references to the menu strip hanging around after the controls were disposed. I changed the code to explicitly set the ContextMenuStrip property to null before disposing of the control, and yep, the memory is now released. Why is this? Shouldn't the GC clean up this type of thing?


If you take a look at the ContexmenuStrip property of Control, you will see that the setter subscribes the control to the Disposed event of the MenuStrip, creating a back-reference from the MenuStrip to the Control.

This means it is a classic case of reachable-through-event and you already found the solution: set the ContexmenuStrip property to null.


You should always dispose ContextMenuStrip in case you create it every time dynamical. This is because every time is a native handle created, but not destroyed. This means if you create contextmenu and show it, then close it and show it again you will run out of handles.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号