Blog de JP Gouigoux

Retours d'expériences .NET d'un architecte logiciel

[TechDays2010] Détection de fuites mémoire en .NET

Executive summary : La CLR .NET se charge de la gestion de mémoire. Il ne devrait donc jamais y avoir de fuites… Vous avez certainement déjà entendu cette erreur. Eh bien si, car seule la mémoire managée est gérée. Tout ce qui est lié à des ressources ou handles Win32, ou bien en interop mémoire, peut poser problème. La session montre aussi que c’est souvent des problèmes liés aux évènements desquels on oublie de se désabonner, en particulier lorsque ce sont des évènements statiques, car la durée de fixation des dépendances est alors la durée de vie de l’application.

La session est présentée par Yann Schwartz et Fabrice Marguerie, tous deux architectes .NET, respectivement chez Polom et MetaSapiens.

Principes

D’abord, une petite introduction est faite sur la gestion de la mémoire .NET. La gestion de la mémoire en .NET est réalisée par la CLR, et le Garbage Collector est responsable du recyclage de la mémoire. Par contre, il y a bien sûr des cas où on ne peut pas libérer la mémoire :

  • Références statiques
  • GCHandle (ce qui fait le lien mémoire dans le cas d’interopérabilité)
  • Références des piles (une par thread)
  • Finalization queue

Et encore on ne parle pas du code non managé.

Détection et correction

On commence avec perfmon.exe, le moniteur de performances de Windows, en ajoutant un compteur Processus / Octets privés pour l’application en question.

Attention, ce n’est pas parce que la mémoire augmente que la mémoire n’est pas relâchée. Donc, on met un bouton dans l’application pour forcer le garbage collection (ça peut être intéressant de mettre un bouton caché dans une application pour ça). Et si effectivement le compteur ne redescend pas lors du GC, c’est vraiment une fuite.

Approches complémentaires :

  • dotTrace pour un audit de haut niveau
  • .NET Memory Profiler pour plus de détails
  • WinDbg pour aller vraiment au fond des choses

JetBrains DotTrace

On commence par une démonstration de dotTrace. On regarde les root paths sur l’instance de l’objet qui garde de la mémoire. Microsoft.Win32.SystemEvents est une liste d’évènements statiques qui restent en vie toute la durée de l’application. Du coup, si une instance reste abonnée, elle ne peut pas être purgée.

Si on fait deux snapshots dotTrace, on a ensuite des icones pour faire du différentiel, voir les nouveaux objets, etc. On voit par exemple que l’application test s’abonne pour une fenêtre à l’événement SystemEvents.InstalledFontsChanged et ne s’en désabonne pas sur l’événement Disposed(). Note : on ne peut pas le faire sur la surcharge du Dispose() car elle est déjà réalisé dans le designer de la WinForms.

L’abonnement à un évènement fait qu’on vit autant de temps que l’objet exposant l’évènement. En effet, en interne, on passe un point d’entrée de fonction à un délégué sur une autre classe pour qu’elle nous appelle sur cette fonction. Du coup, ceci vaut pour un évènement statique, de manière drastique car c’est lié à la vie complète de l’application, mais aussi pour n’importe quel évènement exposé par un objet qui serait lui-même non supprimé par le garbage collector.

SciTech .NET Memory Profiler

Le produit est aussi commercial. Il permet contrairement à dotTrace de se brancher sur une application en cours. Il permet également l’analyse de dump mémoire post-mortem.

Cet outil donne des conseils, en relevant par exemple les instances qui ont été disposées, mais sont encore en vie. Typiquement, la fenêtre est fermée, et le Dipose() est donc appelé immédiatement en WinForms, mais il y a encore des instances qui pointent sur elle.

Attention, on a le même problème sur les closures dans des implémentations d’évènements avec des méthodes lambda.

WinDbg

Débogueur natif et managé, avec un mode graphique et une installation minimale pour pouvoir être placé sur un serveur en production si nécessaire (30 Mo).

Extensions managées : sos.dll pour la gestion mémoire. cmdtree permet d’afficher une fenêtre avec des raccourcis pour charger sos, l’utiliser, etc.

!DumpHeap, !DumpObject, et !GCRoot sont les trois commandes les plus utilisées. Elles permettent de voir le tas, de faire un espion sur un objet particulier, et de voir toutes les racines utilisées.

La liste de commandes réalisées est la suivante :

  1. !DumpHeap –stat –type MonApplication pour voir nos objets.
  2. !DumpHeap –mt Identifiant du type concerné.
  3. !do (abréviation du DumpObject) Identifiant de l’objet.
  4. !GCRoot Identifiant de l’objet.

Dans le cas d’exemple, on se rend compte que l’abonnement à un évènement statique est fait par le ContextMenu de WinForms. Du coup, il est essentiel de bien faire un Dispose(), si on ne passe pas par le designer. Quand on passe par le designer, il crée un ContextMenuStrip en lui passant this.Components, c’est-à-dire en se plaçant dans le container. Du coup, le Dispose() du container parcours tous les contrôles contenus et fait le Dispose() en automatique.

Dernier cas de problème

Plus le temps de faire le reste de la démo complète, mais ProcessExplorer de SysInternals permet de voir des choses en plus, en particulier les processus .NET sont en jaune. On voit dans l’exemple que csc.exe est sans arrêt lancé. Comme on génère des librairies en mémoire pour les XmlSerializer (bug sur le constructeur avec plus d’un paramètre, qui ne met pas en cache), et que l’AppDomain ne peut pas les décharger, on se retrouve à garder la mémoire occupée.

Prévention

Il est important de :

  • Bien appeler les Dispose().
  • Enrichir les Dispose() avec les désabonnements.
  • Code compilé à la volée (XSL/T compilé, sérialisation Xml, anciennement RegExp) : mettre dans des AppDomain séparés et les supprimer si nécessaire.
  • Faire attention aux problèmes spécifiques à des technologies.
  • Contrôler la possession des objets : le créateur n’est pas nécessairement celui qui tient l’objet, et donc en charge de leur libération.
  • Bien faire un –= pour chaque +=.
  • Utiliser les using et Dispose.
  • Utiliser si nécessaire des WeakEvents (garde le lien mais pas si il est le seul).
  • EventBroker pour des cas complexes.
  • Au pire, recycler les applications sur les serveurs.

Une bonne idée est d’intégrer un écran de monitoring dans une application, qui permet de suivre les objets en vie dans un logiciel.

VMMap de Sysinternals à voir, ainsi que les autres références que je n’ai pas eu le temps de prendre en note.

Posted: Feb 09 2010, 14:30 by jeanphilippeg | Comments (37) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: .NET | Techdays2010 | CLR

Comments

Fabrice France said:

Merci pour le compte-rendu !
Les transparents et le code source de l'application exemple sont disponibles : weblogs.asp.net/.../...slides-and-source-code.aspx

# February 11 2010, 21:02

weblogs.asp.net said:

Pingback from weblogs.asp.net

TechDays 2010 session slides and source code - Fabrice's weblog

# February 12 2010, 20:41

free porn United States said:

Tu as raison. C'est une trés bonne idée d’intégrer un écran de monitoring dans une application, qui permet de suivre les objets en vie dans un logiciel. Merci pour le bon poste!

# November 17 2010, 18:59

melissa United States said:

Je suis tellement chanceuse que je comprends un peu le français. J'ai été capable de lire le poste et j'ai vraiment aimé ça. Merci

# November 19 2010, 19:59

porn stars Denmark said:

Great post, thank you.

# November 27 2010, 01:17

Columbus Ohio Dentist United States said:

More words that I cannot read. It's okay because I am only here for the links.

# December 24 2010, 14:16

cheap web design United Kingdom said:

very good post, Thanks

# January 29 2011, 07:02

Camera Espion France said:

Le problème de fuite mémoire est un problème bien connu et le garbage collector est la pour ca.

J'ai eu mes plus gros problèmes quand je mêlais le traitement vidéo avec les technologies .net pour utiliser mes petits gadgets espion ici http://www.ultimatespykit.com

# February 09 2011, 02:08

Bondage Porn United States said:

Hei! Great blog, interesting articles. I have the blog like you.
May be you will be interest to read some article about cars news.

# March 05 2011, 21:03

Gay Bondage. United States said:

Thank you for your article. As always, interesting and informative. I fully share your opinion in this matter. With no patience waiting for new articles. Good luck.

# March 16 2011, 21:13

cancel timeshare United States said:

I like the valuable information you provide in your articles. I’ll bookmark your weblog and check again here frequently. I am quite sure I will learn many new stuff right here! Best of luck for the next!

# April 07 2011, 15:15

bankruprc lawyer United States said:

Just want to say your article is as amazing. The clearness in your post is simply excellent and i could assume you are an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please carry on the rewarding work. Thanks & Regards  

# April 07 2011, 15:21

reebok foam roller United Kingdom said:

c'est super! merci Smile

# April 12 2011, 23:53

pandora United States said:

Great sources for fashion news and fashion articles. They have offered many details around the relevant information. I really like this post a lot and i am planning to recommend it to my pals. Brief and practical methods inside post save your time and within the searching process. It's this kind of awesome source or technique that we can't wait to use it. The post is utterly incredible. Thank you for all you could posted and whatever you tell us!
<a href="www.pandora-braceletsuk.com/">pandora uk</a>

<a href="http://www.linksoflondon-uk.co.uk/">links of london friendship bracelets</a>

<a href="http://www.thomassabosaleshop.com/">Thomas Sabo Jewellery</a>

<a href="http://www.anyrosettastone.com/">Rosetta Stone French</a>

<a href="http://www.beatsdres.com/">beats by dre headphones</a>

# April 23 2011, 16:44

Married women looking for married men United Kingdom said:

I enjoyed your post. Merci Beaucoup Smile

# May 07 2011, 02:56

Sipadan Diving United States said:

I agree ;)

# May 08 2011, 21:55

elegant beaded purses United States said:

Nice posts thanks for sharing some of the information.<a href="www.fashionscarvesandshawls.com/beaded-purses.html">elegant beaded purses</a>

# May 13 2011, 18:11

homes for rent United States said:

techies... sigh more and more advancement what could this thing could lead to... for better or for worst?


<a href="http://ownerwiz.com/">apartment listings</a>

# May 20 2011, 01:38

Wifelovers United Kingdom said:

Thanks for the content and the related links, it was what I was looking for Smile

# May 24 2011, 00:38

Isaias Hartman United States said:

Hello there, i like your post a lot. it was easy to read and understand. i was looking for a blog with this kind of topic.

# June 13 2011, 05:18

Table Tennis United States said:

SciTech .NET Memory Profiler est precisement l'outil que je necessitait. Merci beaucoup pour l'information sur détection et correction des cas où on ne peut pas libérer la mémoire.
Tres interressant!

# June 18 2011, 19:22

knockoff handbags United States said:

Cet outil donne des conseils, en relevant par exemple les instances qui ont été disposées, mais sont encore en vie. Typiquement, la fenêtre est fermée, et le Dipose() est donc appelé immédiatement en WinForms, mais il y a encore des instances qui pointent sur elle.

# June 23 2011, 18:10

knockoff handbags United States said:

very good post, Thanks

# June 23 2011, 18:11

SJR Builders group said:

Blogengine is good for blogging as wordpress, My blog also have this same platform

# July 08 2011, 23:11

Shela Spain said:

Memory management under Windows has been always a little tricky, Merci beaucoup

# July 12 2011, 00:56

comfor table fashion shoes United States said:

very good post, Thanks

# July 23 2011, 17:01

credit repair reviews said:

I’m very happy to read this. This is the type of manual that needs to be given and not the random misinformation that is at the other blogs. Appreciate your sharing this greatest info.

# November 29 2011, 15:53

canadagoosesuper said:

lasting <a href="www.canadagoosesuper.com/...10.htm">Canada Goose Mens jacket</a>  materials are just perfect for your discerning taste! Seeking ways to better address the needs of generations of clients and patrons, the Canada goose online today offers the most sensible where you can have during summer or any season, the introduction Canada Goose Winter Jacket of the flyweight. Take a look at these styles that wonderfully complement the kind of action packed pursuits you are in, particularly in the summer or in the fall: The signature sturdy metal zips, the brass studs with seams constructed to be water-resistant, Canada Goose Outlet Sale the buttons and zips are Barbour branded, bespeaking the authenticity. Its frontage design has easy to use four large front pockets with stud fastening flaps. The pocket has an additional inner patch. <a href="www.canadagoosesuper.com/...C2.htm">Canada Goose Womens</a> Montebello Parka These handsome jackets reflect the meticulous care taken to meet the demands of the modern busy life. There is a modifiable tab at the back with a corduroy interior collar. The lining is carefully designed and sewn with shirting weight Canada Goose Men's Yorkville Parka Maize Barbour tartan fabric or other comfortable and breathable fabrics such as duralumin has double facing if the design has no lining. In addition, the Barbour Trouser Flyweight Waxed jacket is created with a polyester inner drip strip to secure dryness inside <a href="http://www.canadagoosesuper.com/">Canada Goose</a> Chilliwack Parka Womens White  during the rainy season.Belstaff is a name associated with manufacturing an assortment of Canada goose. This is a brand that has been bolstered in past few years. Canada goose today carries a great fan following Discount Louboutin because of their comfortable make and elegant outlook.

# November 30 2011, 13:21

credit repair review said:

Thank you for your wonderful submit. Extremely informative and I enjoyed reading it along with your other articles. Many thanks for sharing and continue the wonderful work.

# December 02 2011, 17:14

lexington law said:

Wow, you seem to be very knowledgable about this kind of topics.

# December 15 2011, 20:06

hair regrowth products United States said:

This is great website the content you have share is really useful and informative too. Thanks for sharing

# December 21 2011, 21:21

sun shade sails United States said:

Ecuse me for being old-fashion, but I am not about to be of the same mind with you in this point. Sorry, anyway we look at it from different angle

# December 29 2011, 03:06

bayliner boat covers United States said:

I enjoyed reading this article. I will not say it is something astonishing, but it is good. Besides, thank you for your article. Keep doing nice job

# January 06 2012, 03:19

compare cat insurance said:

Hey, I really enjoyed reading this post……it made my day meaningful... You have a really fun blog, I hope you post more stuff like this soon…thanks a lot

# February 01 2012, 18:29

louboutin People's Republic of China said:

A baby shoes we’re bringing up www.louboutinonlinefactory.com aren’t the actual Christian Louboutin but simply a baby copies, <a href="http://www.louboutinonlinefactory.com/">christian louboutin shoes</a> may just be according additionally accustomed and <a href="http://www.louboutinonlinefactory.com/">christian louboutin boots</a> stylish. Alexa actually absorb the right amount about adorable certificate, about it cinema a baby central factor in the concept of shoes.<a href="http://www.louboutinonlinefactory.com/">christian louboutin sandls</a> But they don’t bills all of us lots of money a free absolute Christian Louboutin an existing. A few of these clones a bit hinderance a huge selection of bucks and is also a bit affordable.
Christian Louboutin, www.christianlouboutinladyshoes.com known best for his heels with the iconic red bottoms, is helping Neiman Marcus celebrate its 20th anniversarty with the launch of "Sole Seekers,"  <a href="http://www.christianlouboutinladyshoes.com/">christian louboutin pumps</a> a social media challenge that asks users to upload Christian Louboutin images into a growing online pictorial spread. The challenge,<a href="http://www.christianlouboutinladyshoes.com/">christian louboutin shoes</a> which will feature entries from Instagram and Twitter, will also be hosted on the Neiman Marcus Facebook page and NMdaily, The Neiman Marcus Blog, according to a company press release. <a href="http://www.christianlouboutinladyshoes.com/">christian louboutin sandals</a> "Sole Seekers" runs Feb. 10 through March 10 when one winner will be selected to receive a pair of Christian Louboutin shoes.
Fashion women http://www.christianlouboutinonlineshop.com" rel="nofollow">www.christianlouboutinonlineshop.com do not miss the opportunity to own Christian Louboutin shoes at reasonable  prices. Christian Louboutin's shoes for every woman elegant. <a  href="http://http://www.christianlouboutinonlineshop.com" rel="nofollow">www.christianlouboutinonlineshop.com/">christian louboutin shoes</a>
In the fashion industry, <a  href="http://http://www.christianlouboutinonlineshop.com" rel="nofollow">www.christianlouboutinonlineshop.com/">christian louboutin pumps</a>Christian Louboutin synonymous with high fashion and quality.  What's the first thing you think when you hear the name Christian Louboutin? <a  href="http://www.christianlouboutinonlineshop
.com/">christian louboutin boots</a>Your first  thought is a fantasy and charm, right?http://www.christianlouboutinonlineshop.com" rel="nofollow">www.christianlouboutinonlineshop.com
High Christian Louboutin www.christian-louboutin-shopping.com heel boots are shoes with long heels that provide support to the heels and provide an elevation to the feet. Though this form of shoe was introduced keeping in mind women with short <a href="http://www.christian-louboutin-shopping.com/">christian louboutin shoes</a>heights, today these are popular among all women across the world. These sexy looking boots are among the hottest fashion items and are available in a variety of designs and sizes. In the world of fashion, <a href="http://www.christian-louboutin-shopping.com/">christian louboutin outlet</a> trends do not last long and keeping that in mind, the shoe and boot designers and manufacturers keep introducing new collections. Though high heel shoes or boots are meant mainly for women, this footwear is <a href="http://www.christian-louboutin-shopping.com/">christian louboutin boots</a>largely popular between both genders. High heel men boots are also available in quite a number of varieties and sizes.

# March 28 2012, 13:55

Beats By Dre Headphones Australia said:

Beats By Dre Headphones

# April 11 2012, 13:19

red bottom shoes United States said:

Christian Louboutin http://www.redbottomshoesstores.com Platforms Outlet Lady Peep 150mm Shoes<a href="http://www.christianlouboutinsshopping.com/christian-louboutin-miss-tack-85mm_p345"title="Christian" rel="nofollow">www.christianlouboutinsshopping.com/christian-louboutin-miss-tack-85mm_p345"title="Christian Louboutin Miss Tack 85mm"><strong><em>Christian Louboutin Miss Tack 85mm</em></strong></a><BR><P>If your summer wardrobe needs a pick-me-up, look no further thanChristian Louboutinlady peep 150mm Platform shoes camel to make http://www.christianlouboutinsshopping.com your style statement via shoes. We're reloading our shoe closets for Fall. But with so many greatChristian Louboutin 2012available this season, we're having trouble choosing what to buy without breaking the bank. Camel leatherhttp://www.monstersbeatscable.com
http://www.canadagoosefr.com
http://www.primecanadagoose.com
http://shopbrandsale.com and high platform detailing make this pump a real winner. We also love the pretty peep toe detail. Christian once said that a "Christian Louboutin Platforms has so much more to offer http://uschrstianlouboutin.comthan just to walk." Our beautiful "Lady Peep" gives you just that. Slip her on and you'll find that wherever you wear her, you'll be the most confident girl in the room. To be a sexy woman!</P><P></P><P></P><P>Christian Louboutin Platforms Outlet Lady Peep 150mm Shoes</P><P></P><P>OUR FIT SUGGESTIONS:<BR>This style runs true to size.http://www.shopmbtonsale.com<a href="http://www.monstersbeatscable.com/beats-by-dr-dre-studio-nfl-dallas-cowboys-high-definition-on-ear-headphones-sale_p47"title="Beats by Dr Dre Monster Studio NFL Dallas Cowboys High Definition On Ear Headphones"><strong><em>Beats by Dr Dre Monster Studio NFL Dallas Cowboys High Definition On Ear Headphones</em></strong></a></P><P>MATERIAL:Leather</P><P>TECHNICAL INFORMATION:<BR>Heel Height: 6 inches approx. - 150 mm approx.<BR>Arch: 4 inches approx. - 100 mm approx.<BR>Platform Height: 50 inches approx. - 50 mm approx.<BR><a href="uschrstianlouboutin.com/christian-louboutin-outlet-halte-120mm-shoes_p192"title="Christian Louboutin Outlet Halte 120mm Shoes"><strong><em>Christian Louboutin Outlet Halte 120mm Shoes</em></strong></a>COLLECTION:CLASSIQUE</P><P><BR></P><P>Go back to:Christian Louboutin Platforms<a href="http://www.redbottomshoesstores.com/yves-saint-laurent-pumps-platform-shoes-slingback-dark-grey-leather-light-ysl00346_p338"title="Yves Saint Laurent Pumps Platform Shoes Slingback Dark Grey Leather Light YSL00346"><strong><em>Yves Saint Laurent Pumps Platform Shoes Slingback Dark Grey Leather Light YSL00346</em></strong></a></P><P>You might like:</P><P>Christian Louboutin Evening</P><P>Christian Louboutin Slingbacks</P>

# May 14 2012, 19:12

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading

captcha

*