Skip to content

Guard CoreWebView2 access during disposal to prevent COM exception#33920

Draft
Copilot wants to merge 4 commits intomainfrom
copilot/fix-runtime-error-wpf-webview
Draft

Guard CoreWebView2 access during disposal to prevent COM exception#33920
Copilot wants to merge 4 commits intomainfrom
copilot/fix-runtime-error-wpf-webview

Conversation

Copy link
Contributor

Copilot AI commented Feb 5, 2026

WPF Window.Close() during active Blazor event handlers causes CoreWebView2 disposal while SendMessage() attempts COM calls, resulting in exception 0x8007139F.

Changes

WebView2WebViewManager.cs:

  • Added null checks in SendMessage() and NavigateCore() before accessing CoreWebView2
  • Captured reference to local variable to prevent TOCTOU race between check and usage
// Before
protected override void SendMessage(string message)
    => _webview.CoreWebView2.PostWebMessageAsString(message);

// After
protected override void SendMessage(string message)
{
    var coreWebView = _webview.CoreWebView2;
    if (coreWebView != null)
    {
        coreWebView.PostWebMessageAsString(message);
    }
}

Methods now fail silently during disposal instead of throwing, allowing graceful window shutdown.

Original prompt

This section details on the original issue you should resolve

<issue_title>Runtime error when closing external window with WPF Webview Control</issue_title>
<issue_description>### Description

After using the latest WPF Webview control, i created a sample where it opens a popup and i have something to close it. however, it gives a runtime error. The error message was
"System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'"
and this
"COMException: The group or resource is not in the correct state to perform the requested operation. (0x8007139F)
" showed the code that caused it "

CheckArguments(parametersSpan, copyOfArgs, shouldCopyBack, binder, culture, invokeAttr);

 if (_invokeFunc_ObjSpanArgs is not null)
 {
     try
     {
         ret = _invokeFunc_ObjSpanArgs(obj, copyOfArgs);
     }
     catch (Exception e) when ((invokeAttr & BindingFlags.DoNotWrapExceptions) == 0)
     {
         throw new TargetInvocationException(e);
     }
 }

when invoking it.

This did not happen if using the .net 9 version or below.

Steps to Reproduce

  1. Go to my repository here "https://github.com/musictopia2/WebviewControlBug" and run it. click the button that opens a pop window (that was fine)
  2. Close the popup.
    This will always produce the bug.

Link to public reproduction project repository

https://github.com/musictopia2/WebviewControlBug

Version with bug

10.0.11

Is this a regression from previous behavior?

Yes, this used to work in .NET MAUI

Last version that worked well

9.0.120 SR12

Affected platforms

Windows

Affected platform versions

Windows 10

Did you find any workaround?

The workaround was to use the .net 9 version of the component (still works in a .net 10 project).

Relevant log output

```</issue_description>

<agent_instructions>have a look at webview, hybridwebvew and blazorwebview for winui. i recall a related issue around this. investigate this issue and look at the other webview controls that are not having this issue.
</agent_instructions>

## Comments on the Issue (you are @copilot in this section)

<comments>
<comment_new><author>@ilonatommy</author><body>
It is blazor problem, pure WebView does not have it. If we close the window bypassing `Window.Close()` (that is triggered by `StartUp.CloseOut?.Invoke()` ), it works.

It looks like there is a race condition: when we make sure the closing has much lower priority than event handlers it works. The problem might be that the window tries to dispose the `BlazorWebView` while the event handler is still executing.

I was able to find a following workaround for the user's project:
`SampleComponent.razor.cs`

```diff
public partial class SampleComponent(IPopUp pop)
{
    private async Task CloseAsync()
    {
-        StartUp.CloseOut?.Invoke();
+        System.Windows.Application.Current.Dispatcher.BeginInvoke(
+            DispatcherPriority.Background,
+            () => StartUp.CloseOut?.Invoke());
        await pop.ClosedAsync.InvokeAsync();
    }
}
```</body></comment_new>
<comment_new><author>@oroztocil</author><body>
@mattleibow Hi, could you take a look if this could be related to the recent change from `WebView2` to `WebView2CompositionControl`? (See also https://github.com/dotnet/maui/issues/32812)
</body></comment_new>
</comments>

💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot AI and others added 3 commits February 5, 2026 23:55
…osal

Co-authored-by: mattleibow <1096616+mattleibow@users.noreply.github.com>
Co-authored-by: mattleibow <1096616+mattleibow@users.noreply.github.com>
Co-authored-by: mattleibow <1096616+mattleibow@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix runtime error when closing external window with WPF Webview control Guard CoreWebView2 access during disposal to prevent COM exception Feb 5, 2026
Copilot AI requested a review from mattleibow February 5, 2026 23:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Runtime error when closing external window with WPF Webview Control

2 participants