Getting Started with UWP development (13)--checking for memory leaks with diagnostic tool

Source: Internet
Author: User

Because . NET 's garbage collection mechanism is quite perfect, we don't usually need to care about memory leaks. The question person one but silly up, even oneself will be afraid, several pages jumps, jumps, the memory rubs the upward, pulls all cannot pull. At such times we need to calm down and brew a cup of hot chocolate. Then open Visual Studio diagnostic Tools, to check which piece of code is out of the question.

Let's start by creating a simple UWP project that has only 2 nearly empty Page. MainPage has only two buttons to jump to secondpage, and to invoke GC. Collect() method. and Secondpage has only one Goback button, and in the SeCondpage 's constructor creates a large, nearly 400MB ArrayList.

<Page x:class="Eventmemoryleak.mainpage"...> <stackpanel background="{ThemeResource Applicationpagebackgroundthemebrush}"Verticalalignment="Center"> <button click="Button_Click">go to second page</button> <button click="Button_click_1">force gc</button> </StackPanel></Page> Public Sealed Partial classMainpage:page { PublicMainPage () { This.        InitializeComponent (); }        Private voidButton_Click (Objectsender, RoutedEventArgs e) {             This. Frame.navigate (typeof(Secondpage)); }        Private voidButton_click_1 (Objectsender, RoutedEventArgs e) {GC.        Collect (); }    }<Page x:class="Eventmemoryleak.secondpage"...> <grid background="{ThemeResource Applicationpagebackgroundthemebrush}"> <button click="Button_Click">go back to main page</button> </Grid></Page> Public Sealed Partial classSecondpage:page { PublicArrayList ArrayList {Get;Set; }  PublicSecondpage () { This.            InitializeComponent (); ArrayList=NewArrayList (100000000); }        Private voidButton_Click (Objectsender, RoutedEventArgs e) {             This.        Frame.goback (); }    }

When you Debug a UWP program in Visual Studio , the Diag nostic Tools window opens automatically (it doesn't matter if you don't open it, you can go through D Ebug->show Diagnostic Tools found).

After each jump from MainPage to Secondpage, the memory will increase significantly.  


After I write down this paragraph, and then go back to the running program, after MainPage click on the "forceGC" button, theCLR face did a thorough recycling, memory consumption back to the state of the program just opened. What needs to be explained here is that the GC is called . the Collect method does not guarantee that all objects with a reference count of 0 are immediately reclaimed and all memory is freed. The CLR will decide for itself how to recycle, how much to recycle, it is the little public who of pride.

< Span lang= "en-US" > /span>

That's not to say proud Tools is not reliable? Not too! First call gc method, recycling is bound to be executed, there must be a part of the object is released, this part of the change we can through snapshot 23 times gc. Collect method, the effect is very good. Again proud of small public who continuously received "in", will also reply to "Oh, sleep" meaning.

Next we want to deliberately create a serious memory leak and use Diagnostic Tools to observe. We add a service layer class and listen for service layer events in Secondpage . At the same time I changed the arrarylist created by Secondpage from 400MB to 40MB because I was unable to support the performance of the lightweight notebook.

     Public classFakeservice { Public StaticFakeservice Instance =NewFakeservice ();  Public EventEventHandler showmethemoneyevent; PrivateFakeservice () {}} PublicSecondpage () { This.            InitializeComponent (); ArrayList=NewArrayList (10000000); FakeService.Instance.ShowMeTheMoneyEvent+=instance_showmethemoneyevent; }


This time you will find that no matter how you do GC(How to feel this name is a bit dirty ...). I don't know anything about it, and the memory doesn't go down. This is because secondpage is referenced by Fakeservice andFakeservice is a static object that survives the entire APP life cycle, so the secondpage will no longer be released by recycling. Oh, my god .

Do not rush to call, with Snapshot in comparison of memory objects, there will be more terrible things happen. We rerun the program and do a Snapshot at the first run to MainPage . Repeatedly open 3 times seconcdpage, and then return to MainPage do the second time SnapShot.


only added 43heap Size is already miserable. Clicking (+43secondpage3 times when the page is opened, There are 3

Click on the Secondpage line in the list, and in the window below the screen, the Path to Root is displayed , and you can see that the secondpage object is The EventHandler is associated to the Fakeservice object.

  At this point, we found the cause of the memory leak through diagnostic tools, the processing method is also very simple, when leaving the page, the interception of the event is OK, here we can do in the page Onnavigatefrom method.

protected Override void Onnavigatedfrom (NavigationEventArgs e)        {            base. Onnavigatedfrom (e);             -= instance_showmethemoneyevent;        }

In this article we briefly discuss how to use diagnostic tools to observe memory objects and provide a solution to the memory leaks caused by events that listen to static objects. Hope to be able to introduce a lot of insights, the most incompetent you also point a recommendation Bai.



Getting Started with UWP development (13)--checking for memory leaks with diagnostic tool

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.