MicrosoftEdge/WebView2Feedback

The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)

KelvinDong opened this issue · 25 comments

my development enviroment are follow:
visual Studio 2019
Microsoft Edge Canary 86.0.585.0
Microsoft.Web.WebView2 0.9.579-prerelease

My software is base on windows Forms, which function is to open two forms, both package a webview2.
when debug software,it work, but sometimes it don't work by follow execption:

引发的异常:“System.Runtime.InteropServices.COMException”(位于 mscorlib.dll 中)
“System.Runtime.InteropServices.COMException”类型的异常在 mscorlib.dll 中发生,但未在用户代码中进行处理
The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)

at form2.cs :
async void InitializeAsync()
{
----exception-->>>>await webView.EnsureCoreWebView2Async(null);
webView.CoreWebView2.WebMessageReceived += MessageFromWebContent;
}

form1.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;

namespace WindowsFormsWebView2
{
    public partial class Form1 : Form
    {
        Form2 form2;

        Screen childerScreen = null;

        public Form1()
        {
            InitializeComponent();
            this.Resize += new System.EventHandler(this.Form_Resize);
            InitializeAsync();

        }

        // 一定等到webView准备好时,才绑定接收消息方法,异步操作。
        async void InitializeAsync()
        {
            await webView.EnsureCoreWebView2Async(null);
            webView.CoreWebView2.WebMessageReceived += MessageFromWebContent;
            webView.NavigationCompleted += webViewLoadComplete;
        }

        void webViewLoadComplete(object sender, CoreWebView2NavigationCompletedEventArgs args)
        {
            Console.WriteLine(args.IsSuccess); // 只能判断网络错误,并不能判断 404 500的问题。
            Console.WriteLine(args.WebErrorStatus);
            ///StartForm2(childerScreen);
            webView.NavigationCompleted -= webViewLoadComplete;
        }

        void MessageFromWebContent(object sender, CoreWebView2WebMessageReceivedEventArgs args)
        {
            Message message = JsonConvert.DeserializeObject<Message>(args.TryGetWebMessageAsString());

            switch (message.frame)
            {
                case "MASTER":
                    webView.CoreWebView2.Navigate(message.url);
                    break;
                case "SLAVE":
                    if (form2.IsDisposed) 
                    {
                        try
                        {
                            form2 = new Form2();
                            form2.parentForm = this;
                            Screen[] screens = System.Windows.Forms.Screen.AllScreens;
                            if (screens.Length >= 2)
                            {
                                Screen childerScreen = screens[0];
                                for (int i = 0; i < screens.Length; i++)
                                {
                                    if (screens[i].Primary)
                                    {
                                        
                                    }
                                    else
                                    {
                                        childerScreen = screens[i];
                                    }
                                }
                                form2.FormBorderStyle = FormBorderStyle.None;
                                form2.StartPosition = FormStartPosition.Manual;
                                form2.Width = childerScreen.Bounds.Width;
                                form2.Height = childerScreen.Bounds.Height;
                                form2.Location = childerScreen.WorkingArea.Location;
                            }
                            else
                            {
                                form2.StartPosition = FormStartPosition.CenterScreen;//子窗体居中显示                                
                            }
                            form2.InitUrl = message.url;
                            form2.Show();

                        }
                        catch (Exception ex)
                        {
                            //错误日志处理
                        }
                    }
                    else
                    {
                        form2.Activate();
                        form2.WebView.CoreWebView2.Navigate(message.url);
                    }
                    break;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
            try
            {
                //this.TopMost = true;               
                Screen[] screens = System.Windows.Forms.Screen.AllScreens;
                if (screens.Length >= 2)
                {
                    Screen masterScreen = null;
                    for (int i=0 ; i< screens.Length; i++)
                    {
                        if (screens[i].Primary)
                        {
                            masterScreen = screens[i];
                        }
                        else
                        {
                            childerScreen = screens[i];
                        }
                    }

                    this.StartPosition = FormStartPosition.Manual;
                    this.FormBorderStyle = FormBorderStyle.None;
                    this.Width = masterScreen.Bounds.Width;
                    this.Height = masterScreen.Bounds.Height;
                    this.Location = masterScreen.WorkingArea.Location;

                                     
                }                                
            }
            catch (Exception ex)
            {
                //错误日志处理
            }            
            webView.Size = this.ClientSize - new System.Drawing.Size(webView.Location);
            webView.Source = new Uri(Properties.Settings.Default.masterUrl);

            StartForm2(childerScreen);
        }

        async void StartForm2( Screen screen )
        {
            await Task.Delay(50);
            form2 = new Form2();
            form2.parentForm = this;

            if(screen != null)
            {
                form2.FormBorderStyle = FormBorderStyle.None;
                form2.StartPosition = FormStartPosition.Manual;
                form2.Width = screen.Bounds.Width;
                form2.Height = screen.Bounds.Height;
                form2.Location = screen.WorkingArea.Location;
            }
            else
            {
                form2.StartPosition = FormStartPosition.CenterScreen;//子窗体居中显示  
            }
            form2.InitUrl = Properties.Settings.Default.slaveUrl;
            form2.Show();
        }

        private void Form_Resize(object sender, EventArgs e)
        {
            webView.Size = this.ClientSize - new System.Drawing.Size(webView.Location);            
        }


        /*  框架发送消息至web content  本项目不需要此功能
        private void button2_Click(object sender, EventArgs e)
        {
            if (webView != null && webView.CoreWebView2 != null)
            {
                webView.CoreWebView2.PostWebMessageAsString("我来自框架");
            }

                 

        }
        */
    }
}

form2.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;

namespace WindowsFormsWebView2
{
    public partial class Form2 : Form
    {

        public Form1 parentForm;

        public String InitUrl = "";

        public Form2()
        {
            InitializeComponent();
            this.Resize += new System.EventHandler(this.Form_Resize);
            InitializeAsync();
        }

        async void InitializeAsync()
        {
            await webView.EnsureCoreWebView2Async(null);
            webView.CoreWebView2.WebMessageReceived += MessageFromWebContent;
        }

        void MessageFromWebContent(object sender, CoreWebView2WebMessageReceivedEventArgs args)
        {
            Message message = JsonConvert.DeserializeObject<Message>(args.TryGetWebMessageAsString());

            switch (message.frame)
            {
                case "MASTER":
                    parentForm.Activate();
                    parentForm.WebView.CoreWebView2.Navigate(message.url);
                    break;
                case "SLAVE":                    
                    webView.CoreWebView2.Navigate(message.url);                    
                    break;
            }

        }

        private void Form2_Load(object sender, EventArgs e)
        {            
            webView.Size = this.ClientSize - new System.Drawing.Size(webView.Location);
            webView.Source = new Uri(InitUrl);
            
        }
        private void Form_Resize(object sender, EventArgs e)
        {
            webView.Size = this.ClientSize - new System.Drawing.Size(webView.Location);
           
        }

        private void webView_Click(object sender, EventArgs e)
        {

        }
    }
}


The control must be initialised and interacted with on the UI thread. Both Windows Forms controls and the WebView2 COM are STA objects. Because you're not awaiting InitializeAsync(); it is done on a background thread, which leads to the exception.

in form1.cs when replace await Task.Delay(50); to await Task.Delay(1000);, it works.

but on window7 it throws the same exception.

The control must be initialised and interacted with on the UI thread. Both Windows Forms controls and the WebView2 COM are STA objects. Because you're not awaiting InitializeAsync(); it is done on a background thread, which leads to the exception.

in form2.cs InitializeAsync(); , it is awaiting. EnsureCoreWebView2Async is a async method.

async void InitializeAsync()
        {
            await webView.EnsureCoreWebView2Async(null);
            webView.CoreWebView2.WebMessageReceived += MessageFromWebContent;
        }

if I delete the webview2 and related code in form1cs, the form2 works.

Hello,

I met this error, too.
My development environment is as below:

Visual Studio 2019
Microsoft Edge Version 86.0.615.0 (Official build) canary (64-bit)
Microsoft.Web.WebView2 0.9.579-prerelease
Microsoft Edge WebView2 Runtime Version 86.0.698.2

I used WPF to open a window with WebView2.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Web.WebView2.Core;

namespace Demo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        bool _isNavigating = false;


        public WebView(string path)
        {
            InitializeComponent();
            var uri = new Uri(path);
            webView.Source = uri;
            InitializeAsync();
        }

        async void InitializeAsync()
        {
            await webView.EnsureCoreWebView2Async(null);
            webView.NavigationCompleted += WebView_NavigationCompleted1;
        }
    }
}

I run the WebView2WpfBrowser from https://github.com/MicrosoftEdge/WebView2Samples/tree/master/SampleApps and met the same error

We recently made a change to fix trying to load two WebView2 controls in Winforms at the same time. The fix should be available in 1.0.674-prerelease. I'm going to close this issue, but if that doesn't fix it for you please let me know and I can reopen. Thanks!

I ran into the same error, I followed https://docs.microsoft.com/en-us/microsoft-edge/webview2/gettingstarted/win32?WT.mc_id=DT-MVP-5003235 and only created a new (blank) form in where the webview2 is.
I set the Source property to localhost. Every other run the webview doesn't load the localost/index.html (it stays blank) and when resizing the window this exception is thrown.
I am on 1.0.674-prerelease

@nonsensation Sounds like your issue is specific to localhost - does it work fine if you use something else, like https://bing.com? If it is related to localhost, please open a new issue: https://github.com/MicrosoftEdge/WebView2Feedback/issues/new/choose

Update: I was using this python http.server :

from http.server import HTTPServer, SimpleHTTPRequestHandler

class CORSRequestHandler(SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET')
        self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
        return super(CORSRequestHandler, self).end_headers()

httpd = HTTPServer(('localhost', 8000), CORSRequestHandler)
httpd.serve_forever()

What seems like to be my issue. Using Z-WAMP fixed it.

I keep and keep running into this issue. I am on 1.0.674-prerelease and even though I tried hedging my code with ways to dispose of WebView2 before moving on from the code that executes the relevant parts, the error keeps popping up. This is quite frustrating, sure there must be a way to make the control safer to use. It is quite unstable at the moment.

If this is helpful for someone, an issue that I found was that trying to dispose of the webView2 failed if I did not release it from the parent control that was hosting it in my view.

@dnenov This error is a bit of a catchall at the moment unfortunately. We have a fix for the dispose issue that just missed this recent SDK release but should be in the next one. If you have specific repro steps or scenarios you are running into please open a new issue with the details and we can try and help. Thanks!

@dnenov I have the same issue, I seem to have fixed the exception by exposing the webview2's dispose directly to the parent component and calling it on FormClosing event, instead of relying on IDisposable to make the call when disposing of the parent component.

Environment: WPF, .net 5, VS 2019 on Win 10 x64, WebView2 1.0.705.50
I have the same exception thrown randomly when changing from a Tab (in a tab control) to another tab, I have three Webview2 controls and all of them are initialized in the Load Event with the appropriate await. They work correctly and then randomly when changing the Tab this exception is thrown and the application is shut down.
Is there at least a place where to catch the exception?
Thank You in advance

@SabrinaCs This error can sometimes happen if the browser process crashes. Can you try subscribing to the ProcessFailed event and see if it's the browser process that's crashing?

I can try subscribing the event, but I don't see it as part of the WebView2 nor the Application, so which component has that Event?
thank you in advance
Sabrina

The ProcessFailed event is on the CoreWebView2 object.

WebView2.CoreWebView2.ProcessFailed += ...

https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.processfailed?view=webview2-dotnet-1.0.705.50

I get this error when simply clicking on the close button of the form that hosts my WebView2 control:

image

Otherwise WebView2 is a great drop-in replacement for the old .net WebBrowser control.
It works fine in .net5 and hosts my Blazor server app. so far without problems.

Experiencing the same exception when I shutdown my machine before exiting my application using WebView2 1.0.705.50. The expected behavior would be for the application to exit gracefully then the machine would shutdown.

The ProcessFailed event is on the CoreWebView2 object.

WebView2.CoreWebView2.ProcessFailed += ...

https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.processfailed?view=webview2-dotnet-1.0.705.50

I've set the event handlers in my application I'll let you know if the exception is intercepted and what kind it is.
Thank you
Sabrina

Anyone working on this? Or any updates? I'm seeing this too in a VSTO plug-in with .NET 4.7.

Any update on this? I am seeing the issue when right click on any hyperlink. I tried with both release and latest prerelease but the issue is seen in both.
To reproduce the issue:
`Set webView2 Source as 'https://www.bing.com'. Search for 'WebView2'. Right click on any link shown in the search result.

Exception Details:
System.Runtime.InteropServices.COMException
HResult=0x8007139F
Message=The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)
Source=Microsoft.Web.WebView2.Core
StackTrace:
at Microsoft.Web.WebView2.Core.Raw.ICoreWebView2Controller.MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON reason)
at Microsoft.Web.WebView2.Core.CoreWebView2Controller.MoveFocus(CoreWebView2MoveFocusReason reason)
at Microsoft.Web.WebView2.Wpf.WebView2.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndHost.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
`

@smohanty05 You are running into the same issue as #1081. We have a fix that will be deployed this week. Thanks!

I observer same Behaviour as @SabrinaCs, was this solved? Can anyhone help on this?
Environment: WPF, .net Framework 4.5.2, VS 2019 on Win 10 x64, WebView2 1.0.818.41
Thanks

Environment: WPF, .net 5, VS 2019 on Win 10 x64, WebView2 1.0.705.50
I have the same exception thrown randomly when changing from a Tab (in a tab control) to another tab, I have three Webview2 controls and all of them are initialized in the Load Event with the appropriate await. They work correctly and then randomly when changing the Tab this exception is thrown and the application is shut down.
Is there at least a place where to catch the exception?
Thank You in advance

hjlld commented

I encountered the same issue, but in my app i have only one webview2, after app starting, a few seconds later, even if you don't touch it, webview2 will turn to gray and then black. The webview.CoreWebView2.ProcessFailed event is fired, it says that the webview process is crashed.

c# winform, .net Framework 4.7.2, VS2019, Win10 21H1 19043.1165, Webview2 1.0.955-prerelease, Edge 94.0.989.0 canary (64 bit)

EnsureCoreWebView2Async didnt help in my case.
The only thing that worked was to uninstall and reinstall webview2 runtime from apps & features.