WebView & UWP – Freeing up Memory

This week I was working on a Universal Windows Platform app that needs to show a website inside a WebView for several hours at a time. Unfortunately after a few hours the app took all the RAM it could get due to some memory leaks inside the WebView which I don’t have any control over.

My first attempt to fix this was to refresh the site periodically. Unfortunately this doesn’t seem to release the memory – I think it made things even worse. So I tried a different method, which works quite well for now.

I ended up creating the WebView completely in the code-behind and not in XAML so it would be easy to get rid of the whole control and just rebuild it from time to time. One thing I’ve not done before is creating a Viewmodel-binding in C#, but it’s not that hard either when you see the syntax (I still prefer the XAML-way, though).  This is what the code looks like:

private readonly MainViewModel _vm;
private DispatcherTimer _idleTimer;
private WebView MyWebView;

private void initWebView()
{
    MyWebView = new WebView();

    // Set WebView binding
    var binding = new Binding();
    binding.Source = _vm;
    binding.Path = new PropertyPath("Url");
    binding.Mode = BindingMode.OneWay;
    binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
    BindingOperations.SetBinding(MyWebView , WebView.SourceProperty, binding);

    // add WebView to View
    MainGrid.Children.Add(MyWebView);
    MyWebView.LoadCompleted += MyWebView_LoadCompleted;
    _idleTimer.Reset();
}

private void reload WebView()
{
    // getting rid of old WebView
    MainGrid.Children.Remove(MyWebView);
    MyWebView = null;
    GC.Collect();

    // create new WebView
    initWebView();
}

I have created a DispatchTimer _idleTimer that will force the WebView to reload after a certain time. How often that’s necessary depends on the machine the app is running on and the website that’s being displayed. I’ve also made sure to reset the timer as long as there are input events so the WebView won’t disappear while being used.

Let me know if this did help you and if you have any suggestions!

2 thoughts on “WebView & UWP – Freeing up Memory”

  1. Good one. That helped me do the same. Note that BindingMode probably should be set to TwoWay mode if you want to get feedback on a browser redirection. ln my case I also use ‘new WebView(WebViewExecutionMode.SeparateThread)’ which helps with performance…

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.