Is this a memory leak in Xamarin Forms?

后端 未结 1 564
长发绾君心
长发绾君心 2021-02-07 05:00

I have run into a problem where it appears Page objects are not being Garbage Collected once they have been navigated away from. I have put together a very basic example of thi

1条回答
  •  南方客
    南方客 (楼主)
    2021-02-07 05:40

    I think what you are seeing is a side effect of async navigation, not memory leak. Instead of WeakReferences you might opt for a finalizer instead and create instances of MyPage (instead of ContentPage).

        public class MyPage: ContentPage
        {
            private static int count;
    
            public MyPage()
            {
                count++;
                Debug.WriteLine("Created total " + count);
            }
            ~MyPage()
            {
                count--;
                Debug.WriteLine("Finalizer, remaining " + count);
            }
        }
    

    Next trick is to add a delayed GC.Collect() call, like:

        private static Page CreateWeakReferencedPage()
        {
            GC.Collect();
            var result = CreatePage();
            var ignore = DelayedGCAsync();
            return result;
        }
    
        private static async Task DelayedGCAsync()
        {
            await Task.Delay(2000);
            GC.Collect();
        }
    

    You will note that instances get garbage collected within this delayed collection (output window). As per Xamarin GarbageCollector: I doubt that it has serious flaws. A minor bug here and there but not that huge. That said, dealing with garbage collections in Android is particularly tricky because there are two of those - Dalvik's and Xamarin's. But that is another story.

    0 讨论(0)
提交回复
热议问题