'Why does EnsureCoreWebView2Async only return in OnContentRendered

I'm trying to use WebView2 in a WPF (.NET Framework) application, and I'm puzzled by the method EnsureCoreWebView2Async.

I followed the Getting Started article, and surely enough it was not working for me. The method EnsureCoreWebView2Async would never return.

Took a look at this answer which suggests (with no further explanation) to call the method in the OnContentRendered callback.

While this works, is there any reason why this happens ? With the following code :

public partial class DocumentationWindow : Window
{
    public DocumentationWindow(Window owner, DocumentationViewModel vm)
    {
        Owner = owner;
        DataContext = vm;
        InitializeComponent();
        InitializeAsync();
    }

    private async void InitializeAsync()
    {
        await webView.EnsureCoreWebView2Async(null); // This will never return
    }
    
    protected override async void OnContentRendered(EventArgs e)
    {
        base.OnContentRendered(e);
        await webView.EnsureCoreWebView2Async(); // This will work just fine
    }
}

The doc states

Note that even though this method is asynchronous and returns a Task, it still must be called on the UI thread like most public functionality of most UI controls.

Both the constructor and OnContentRendered are excecuted on the UI thread.

But somehow, the former will never return. Why is that ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source