memorywinui-3winuiwinui-xaml

Memory is not getting released in WinUI application


I have a WinUI application, which uses Newtonsoft.Json for json serialization and use x:Bind for binding the value to xaml UI. There are various UI elements like, listview, gridview, buttons, contentdialog, tab view etc in the page.

When i continuously use the application for around one hour, I could see the memory of the app being raised huge. i.e, While the start of application the apps memory will be 240MB, upon one hour of usage it goes to 600MB.

Upon running the memory analyzer, i could see the memory reserved by the string objects use around 140MB, even though those objects are not in use, the memory allocated is not getting cleared.

Additionally, I have observed a case where there is a memory increase, whenever i switch tabs, i.e, while each tab switch 2mb of memory is raised. After certain time, it is getting reduced.

Have anyone faced such scenarios and overcame it?


Solution

  • As I mentioned in comments, the properties used the viewmodels where not properly cleared when it is destroyed. What I have done is, I have written a method called "CleanUpProperties" this will be invoked while the dispose method is called. This will set all the properties in the viewmodel with default values.

    public void CleanupProperties(bool isclass = false)
    {
        // Get all properties of the current object
        var properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var property in properties)
        {
            if (property != null)
            {
                if (!property.CanWrite)
                    continue; // Skip properties that cannot be written to
    
                var propertyType = property.PropertyType;
    
                if (propertyType.IsValueType)
                {
                    // For value types, set the property to its default value
                    property.SetValue(this, Activator.CreateInstance(propertyType));
                }
                else if (propertyType == typeof(string))
                {
                    // For strings, set to null
                    property.SetValue(this, null);
                }
                else if (propertyType.IsClass)
                {
                    // For reference types, set to null
                    property.SetValue(this, null);
                }
            }
        }
    }
    

    Note: This may be my app specific case where the properties are not being cleared. Sharing the solution found here so that anyone else struck with my similar problem might get use of it.