2

Problem:

WebView not releasing memory after loading images.

The memory does seem to get released if all WebView instances are destroyed for few seconds. We removed from XAML tree and all references in code cleared. (We checked in debugger that all instances were released at that point.)

This solution is problematic since the web view must be dead for a while for the memory clearing to kick in and is unacceptable for our use case.

How to reproduce:

Make either a UWP C# app or a C++ UWP app -> add a WebView -> load large images with randomized URLs -> Memory keeps growing.

We have only one active WebView and we load a large image in it multiple times one after another. (We randomise part of the image url to simulate different ad loads.)

The memory keeps growing as if the images never get released. What we tried:

  • Clearing cache with WebView.ClearTemporaryWebDataAsync() but it doesnt do anything.
  • Manually triggering GC.

Notes:

  • We initialise webview using this "WebView(WebViewExecutionMode.SeparateThread)". (other execution modes don't seem to help).
  • We do not use a WebViewBrush.

1 Answers1

5

UWP App WebView Leaks Memory, doesn't clear images

WebView is complex element. And it has own garbage collection rules, For keep render performance, it will cache a lot of data that cause memory keeps growing and gc process is slow. we can't have it both ways.

For my experience, you could set the WebView Source as "about:blank" repeatedly that could release most data immediately.

private void AppBarButton_Click(object sender, RoutedEventArgs e)
{
    int count = 0;
    var timer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
    timer.Start();
    timer.Tick += (s, p) =>
    {
        TestWebView.Source = new Uri("about:blank");
        count++;
        if (count == 20)
        {
            timer.Stop();
        }
    };      
}
Nico Zhu
  • 32,367
  • 2
  • 15
  • 36
  • 1
    This works. It's still a bit hacky but it works in practice. Sometimes it takes a few minutes for this to kick in but it does sooner or later. Thanks Nico. – user6410441 Dec 16 '19 at 12:30