fluentui-blazor icon indicating copy to clipboard operation
fluentui-blazor copied to clipboard

fix: webbrowser not freeing ram after component disposal

Open pmi24 opened this issue 1 year ago • 10 comments

🐛 Bug Report

I have a data page where I show a list of entries (500 objects), within a FluentDataGrid. Each row has a FluentAnchor with a FluentTooltip.

  1. Start the application, the browser allocates roughly 25MB of RAM while loading the home page.
  2. Navigate to the data page, the memory consumption climbs up to ~230MB while rendering the data grid.
  3. Navigate back to the home page, the memory increases by ~2MB.
  4. Navigate back to the data page, browser memory climbs up even higher up to ~320MB.

(5. Repeat for infinite memory allocation.)

Things I tried so far:

  • implementing IDisposable on the data page
  • disposing the list
    • list?.Clear();
    • list = null;
  • disposing the @ref object of the FluentDataGrid
    • dataGrid?.DisposeAsync();
    • dataGrid = null;
  • changing / keeping the @key directive of FluentDataGrid on page load
  • navigating by ForceReload = true/false
  • GC.Collect();

No memory is ever released by the browser.

💻 Repro or Code Sample

@implements IDisposable

@if (dataList == null)
{
    <p>No data</p>
}
else
{
    <FluentDataGrid @ref="dataGrid" @key="renderKey" Items="@dataList.AsQueryable()" TGridItem="Data" Virtualize="false">
        <TemplateColumn Title="No">
            @context.No
        </TemplateColumn>
        <TemplateColumn Title="Id">
            <FluentAnchor Href="#" Id="@context.Id">Hover to reveal</FluentAnchor>
            <FluentTooltip Anchor="@context.Id" Position="TooltipPosition.Right">@context.Id</FluentTooltip>
        </TemplateColumn>
    </FluentDataGrid>
}

@code {
    string? renderKey;
    private List<Data>? dataList;
    FluentDataGrid<Data>? dataGrid;

    protected override void OnInitialized()
    {
        renderKey = Guid.NewGuid().ToString();

        dataList = Enumerable.Range(1, 500).Select(i => new Data
            {
                Id = Guid.NewGuid().ToString(),
                No = i
            }).ToList();
    }

    public void Dispose()
    {
        dataList?.Clear();
        dataList = null;

        dataGrid?.DisposeAsync();
        dataGrid = null;
    }

    public struct Data
    {
        public string Id { get; set; }
        public int No { get; set; }
    }
}

🤔 Expected Behavior

On navigating away from any page, the fluent components, their data and all of their child elements should be disposed and removed from the DOM / browser cache and memory consumption of the browser should fall back down to ~25MB.

Or (with caching intention in mind) at least the reloaded page should re-use the cached version of the FluentDataGrid instead of always creating an entirely new one (that is apparently never used again, so why would it be cached in the first place?)

😯 Current Behavior

FluentUI components are never disposed from browser cache on navigation / re-rendering.

💁 Possible Solution

Disposing DOM elements, when leaving page or disposing components.

🔦 Context

  • When spam clicking page navigation for some time, the browser tab crashes because of no memory available.
  • When using Virtualize="false" this issue obviously becomes less impactful, but nevertheless it's still there.
  • I can't observe this behavior when only using default html components

I apologize if I'm doing something wrong, or if I'm misinterpreting intended behavior. But this issue has led my application to easily accumulate up to multiple GBs when in use for a longer time period.

🌍 Your Environment

  • OS & Device: Windows 11 PC 64-bit
  • Microsoft Edge 138.0.3351.83 & Google Chrome 138.0.7204.97
  • .NET 9.0.7 and Fluent UI Blazor library Version 4.12.0

pmi24 avatar Jul 14 '25 15:07 pmi24

Do you observe the same behavior when not using the Anchor and Tooltip?

I suspect the underlying web components are causing this behavior. We've had earlier report on cases where a huge number of buttons were being created. Unfortunately the web components are no longer being maintained and we can't properly address this until the next major release of our components (which will use newer (supported) web components)

vnbaaij avatar Jul 14 '25 15:07 vnbaaij

@pmi24 this is completely normal. Blazor does not free up memory directly. Instead it reuses the memory and only frees up memory once the server is running low on ressources. There are many issues in the aspnetcore repository which report the same behaviour.

https://github.com/dotnet/aspnetcore/issues/59970 https://github.com/dotnet/aspnetcore/issues/49773

For more details see: https://learn.microsoft.com/en-us/aspnet/core/performance/memory?view=aspnetcore-9.0

MarvinKlein1508 avatar Jul 14 '25 22:07 MarvinKlein1508

Closing this based on comment from @MarvinKlein1508 (thanks!)

vnbaaij avatar Jul 15 '25 06:07 vnbaaij

Do you observe the same behavior when not using the Anchor and Tooltip?

It's hard to tell, because w/o the fluent components, significantly less memory is used and there's always a little jitter in RAM allocation, even when loading an empty page.

I suspect the underlying web components are causing this behavior. We've had earlier report on cases where a huge number of buttons were being created. Unfortunately the web components are no longer being maintained and we can't properly address this until the next major release of our components (which will use newer (supported) web components)

That was my suspicion as well. I recorded the memory allocations in Microsoft Edge for both variants, and it appears that the fluent components indeed persist in memory as detached objects.

(I didnt count the number of navigation changes for each example, I just made sure a significant amount of RAM is allocated for both)

w/o FluentAnchor & FluentTooltip: Image

w/ FluentAnchor & FluentToolTip: Image

pmi24 avatar Jul 15 '25 09:07 pmi24

@pmi24 this is completely normal. Blazor does not free up memory directly. Instead it reuses the memory and only frees up memory once the server is running low on ressources. There are many issues in the aspnetcore repository which report the same behaviour.

dotnet/aspnetcore#59970 dotnet/aspnetcore#49773

For more details see: https://learn.microsoft.com/en-us/aspnet/core/performance/memory?view=aspnetcore-9.0

@MarvinKlein1508 Thanks for the input.

However, I’m referring to the web browser’s RAM usage, not the server application’s. As far as I know, garbage collection only applies to the C#-managed code running on the server side.

My concern is that the web components cached in the browser’s (virtual?) DOM are never released. The application’s server-side RAM usage is fine. I haven’t found any issue or article that specifically addresses this case.

Also, I’m all for memory reuse — but if the memory were truly being reused, why would it grow with every rerender? That doesn’t seem like "reuse" to me.

pmi24 avatar Jul 15 '25 09:07 pmi24

@pmi24 yes I'm talking about Blazor Server and not the browsers RAM.

Also, I’m all for memory reuse — but if the memory were truly being reused, why would it grow with every rerender?

I can explain this for Blazor Server. Not sure if the same concept applies to WASM as well. A component is basically nothing else then a C# class which gets created whenever it is being rendered and removed via GC once the Server thinks the component is ready for it.

The same concept applies to circuits in Blazor Server. You may think that the circuit will get removed from memory once you close the tab but Blazor will actually keep the circuit alive for n time in case the same user comes to the tab. For example if you open the page on you mobile browser and switch to another app.

I must admit though that I have never really dig deep into memory things as .NET has always been able to mange this kind of stuff for me as long as I dispose my classes which implement IDisposable.

I have hundred of FluentAnchors and FluentTooltip within my Blazor Server app and I never run into any issue with memory. In fact my app is never using more than 700MB of memory. And I'm rendering some pretty complex UIs here with tabs, anchors, flyouts, dialog, data grids, buttons and co.

MarvinKlein1508 avatar Jul 15 '25 15:07 MarvinKlein1508

@MarvinKlein1508 As I mentioned earlier, my application (.exe) is working fine, and those are not the issues I'm concerned about. I'm using IDisposable, timers/events/objects are being cleaned up and GC is doing its job - my application never exceeds 300 MB of RAM.

If you take a look at my screenshots, you'll see that they are from Microsoft Edge's Developer Tools, not from a C# memory profiler.

My concern is solely about the web browser. It renders Fluent UI's underlying web components, as @vnbaaij pointed out, but it never fully disposes of them from the DOM. This behavior is outside the scope of CLR or managed code (such as garbage collection or circuit disposal mechanisms, etc.).

pmi24 avatar Jul 17 '25 08:07 pmi24

My concern is solely about the web browser. It renders Fluent UI's underlying web components, as @vnbaaij pointed out, but it never fully disposes of them from the DOM. This behavior is outside the scope of CLR or managed code (such as garbage collection or circuit disposal mechanisms, etc.).

As I said, it is an issue with the version of the web components we are currently using. It won't get fixed there anymore.

vnbaaij avatar Jul 17 '25 08:07 vnbaaij

As a workaround I tried disposing all fluent components from the DOM before page unload, via js interop. But sadly, blazor doesn't like it when you mess with it's internally managed stuff and it throws an error and crashes: https://github.com/dotnet/aspnetcore/issues/18708#issuecomment-580834844

See code

Blazor component:

<NavigationLock OnBeforeInternalNavigation="HandleNavigation" ConfirmExternalNavigation="true" />

@code {
    [Inject]
    IJSRuntime JS { get; set; }

    private async Task HandleNavigation(LocationChangingContext context)
    {
        await JS.InvokeVoidAsync("forceDisposeAll ");
    }
}

JS code:

window.forceDisposeAll = function () {
    const elements = document.querySelectorAll('.force-dispose');

    elements.forEach(el => {
        disposeRecursive(el);

        if (el.remove) {
            el.remove();
        } else if (el.parentNode) {
            el.parentNode.removeChild(el);
        }
    });

    function disposeRecursive(element) {
        // Handle custom dispose method
        if (typeof element.dispose === 'function') {
            try { element.dispose(); } catch (e) { console.warn('Error during dispose()', e); }
        }

        // Handle disconnect (common in Web Components)
        if (typeof element.disconnect === 'function') {
            try { element.disconnect(); } catch (e) { console.warn('Error during disconnect()', e); }
        }

        // Recurse into shadow DOM if present
        if (element.shadowRoot) {
            Array.from(element.shadowRoot.children).forEach(child => disposeRecursive(child));
        }

        // Recurse into regular children
        Array.from(element.children).forEach(child => disposeRecursive(child));

        // Remove all event listeners by cloning the node (DOM-only, doesn't cover shadow)
        const clone = element.cloneNode(false);

        while (element.firstChild) {
            element.removeChild(element.firstChild);
        }

        element.replaceWith(clone);
    }
};

@vnbaaij is there a rough ETA on when those new web components will be used?

pmi24 avatar Jul 17 '25 09:07 pmi24

We are currently working on the v5 library (in our own time) which uses the new Web Components (v3). You can follow our progress in the dev-v5 branch. The demo website for that version is at https://fluentui-blazor-v5.azurewebsites.net/. See https://github.com/microsoft/fluentui-blazor/blob/dev-v5/docs/using-latest-daily.md on how you can use the preview packages.

It will be ready when it is ready. We never give out ETAs unless we know something is coming in like the next week or so.

vnbaaij avatar Jul 21 '25 08:07 vnbaaij