Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unhandled Exception types occur during continuously running WinForms program #272

Closed
mikemeinz opened this issue Jun 14, 2020 · 3 comments
Closed
Assignees

Comments

@mikemeinz
Copy link

mikemeinz commented Jun 14, 2020

Unhandled exception types thrown by the WebView2 component
In Auto Mode, my WinForms program runs without user input repeatedly cycling through a ComboBox list of WebCam URIs. After running for some time, many times for several hours, a few different exception types occur that can't be trapped with Try..Catch blocks. During the times that these exceptions occur, the program is calling WebView2.Stop or assigning a URI to WebView2.Source.

The WinForms program is compiled in Release mode for .NET Framework 4.8 and is running as the only user app on a resource constrained Windows 10 Home Version 1909 (OS Build 18363.900) 32 bit OS, x64 Intel Atom CPU N450 1.66GHz processor with 1GB RAM.

Unhandled Exception Types

#1: The group or resource is not in the correct state - Program is able to reinitiate WebView2 and continue running.

10:41:49 Thread Exception
10:41:49 The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)
System.Runtime.InteropServices.COMException (0x8007139F): The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)
   at Microsoft.Web.WebView2.Core.Raw.ICoreWebView2.Stop()
   at Microsoft.Web.WebView2.Core.CoreWebView2.Stop()
   at Microsoft.Web.WebView2.WinForms.WebView2.Stop()
   at WebCam.Main.AutoDisplay() in C:\Users\MM\Documents\Visual Studio 2017\Projects\WebCam\WebCam\Main.vb:line 149
   at WebCam.Main.Timer_Tick(Object sender, EventArgs e) in C:\Users\MM\Documents\Visual Studio 2017\Projects\WebCam\WebCam\Main.vb:line 164
   at System.Windows.Forms.Timer.OnTick(EventArgs e)
   at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
10:42:02 Thread Exception
10:42:02 The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)
System.Runtime.InteropServices.COMException (0x8007139F): The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)
   at Microsoft.Web.WebView2.Core.Raw.ICoreWebView2Controller.set_IsVisible(Int32 IsVisible)
   at Microsoft.Web.WebView2.Core.CoreWebView2Controller.set_IsVisible(Boolean value)
   at Microsoft.Web.WebView2.WinForms.WebView2.OnVisibleChanged(EventArgs e)
   at System.Windows.Forms.Control.WmShowWindow(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
10:42:02 Thread Exception
10:42:02 The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)
System.Runtime.InteropServices.COMException (0x8007139F): The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)
   at Microsoft.Web.WebView2.Core.Raw.ICoreWebView2Controller.set_IsVisible(Int32 IsVisible)
   at Microsoft.Web.WebView2.Core.CoreWebView2Controller.set_IsVisible(Boolean value)
   at Microsoft.Web.WebView2.WinForms.WebView2.OnVisibleChanged(EventArgs e)
   at System.Windows.Forms.Control.WmShowWindow(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
10:42:02 Instantiate WebView2
10:42:02 WebView2 Created
10:42:02 WebView2 Initialized
10:42:13 Instantiate WebView2
10:42:13 WebView2 Created
10:42:13 WebView2 Initialized
10:42:13 Instantiate WebView2
10:42:13 WebView2 Created
10:42:13 WebView2 Initialized

12:49:24 Thread Exception
12:49:26 The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)
System.Runtime.InteropServices.COMException (0x8007139F): The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
   at Microsoft.Web.WebView2.Core.CoreWebView2Environment.<CreateCoreWebView2ControllerAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Web.WebView2.WinForms.WebView2.<InitCoreWebView2Async>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at WebCam.Main.VB$StateMachine_7_InitializeAsync.MoveNext() in C:\Users\MM\Documents\Visual Studio 2017\Projects\WebCam\WebCam\Main.vb:line 28
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_0(Object state)
12:49:30 Instantiate WebView2
12:49:30 WebView2 Created
12:49:30 WebView2 Initialized
12:49:53 http://192.168.0.201/img/video.mjpeg
12:49:55 UnhandledException: e.IsTerminating=True
12:49:55 Unhandled Exception
12:49:55 Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Web.WebView2.WinForms.WebView2.Dispose(Boolean disposing)
   at System.ComponentModel.Component.Finalize()

#2 Error HRESULT E_FAIL has been returned from a call to a COM component - Program is able to reinitiate WebView2 and continue running.

07:27:39 Thread Exception
07:27:39 Error HRESULT E_FAIL has been returned from a call to a COM component.
System.Runtime.InteropServices.COMException (0x80004005): Error HRESULT E_FAIL has been returned from a call to a COM component.
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
   at Microsoft.Web.WebView2.Core.CoreWebView2Environment.<CreateCoreWebView2ControllerAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Web.WebView2.WinForms.WebView2.<InitCoreWebView2Async>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at WebCam.Main.VB$StateMachine_6_InitializeAsync.MoveNext() in C:\Users\MM\Documents\Visual Studio 2017\Projects\WebCam\WebCam\Main.vb:line 22
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_0(Object state)
07:27:43 Instantiate WebView2
07:27:43 WebView2 Created
07:27:43 WebView2 Initialized

#3 Object reference not set to an instance of an object. - Program is sometimes able to continue running.

07:47:03 Unhandled Exception
07:47:03 Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Web.WebView2.WinForms.WebView2.Dispose(Boolean disposing)
   at System.ComponentModel.Component.Finalize()
07:47:06 http://192.168.0.201/img/video.mjpeg

#4 Unable to cast COM object - Program terminates

17:29:17 UnhandledException: e.IsTerminating=True
17:29:17 Unhandled Exception
17:29:17 Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Web.WebView2.Core.Raw.ICoreWebView2Controller'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{7CCC5C7F-8351-4572-9077-9C1C80913835}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Web.WebView2.Core.Raw.ICoreWebView2Controller'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{7CCC5C7F-8351-4572-9077-9C1C80913835}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
   at System.StubHelpers.StubHelpers.GetCOMIPFromRCW(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget, Boolean& pfNeedsRelease)
   at Microsoft.Web.WebView2.Core.Raw.ICoreWebView2Controller.Close()
   at Microsoft.Web.WebView2.Core.CoreWebView2Controller.Close()
   at Microsoft.Web.WebView2.WinForms.WebView2.Dispose(Boolean disposing)
   at System.ComponentModel.Component.Finalize()
17:29:20 Navigation Completed. Error=ErrorHttpInvalidServerResponse


I tried using Try..Catch around the WebView2.Source assignment statements but that did not catch any of these exceptions. I removed the Try.. Catch and added an event handler for Application.ThreadException and an event handler for AppDomain.CurrentDomain.UnhandledException. The program attempts to resume by reinitiating WebView2 when certain thread exceptions occur.

Program Flow Description
The AutoDisplay() method is called by Timer_Tick() every 10 seconds. Within the AutoDisplay() method, WebView2.Stop is called, the ComboBox.SelectedIndex is set to the new index value and the ComboBox.SelectedItem value is assigned to WebView2.Source.

Snippets from the program
The Visual Studio project files are available upon request.

Initialization

    Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        AddHandler Application.ThreadException, AddressOf ThreadExceptionHandler
        AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledExceptionHandler
        InitializeAsync()
    End Sub

    Private Async Sub InitializeAsync()
        Await webView.EnsureCoreWebView2Async
    End Sub

Exception Handlers

    Private Async Sub ThreadExceptionHandler(sender As Object, e As ThreadExceptionEventArgs)
        Timer.Enabled = False
        webViewInitialized = False
        Application.DoEvents()
        Dim terminate As Boolean = Not (Hex(e.Exception.HResult) = "8007139F" Or Hex(e.Exception.HResult) = "80004005")
        WriteException("WebCam.log", e.Exception, "Thread Exception")
        If terminate Then
            Timer.Enabled = False
            MsgBox(e.Exception.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "Thread Exception")
            End
        Else
            Await Task.Delay(10000)
            ReinitializeWebView()
            If autoMode Then
                Timer.Enabled = True
            End If
        End If
    End Sub

    Private Sub UnhandledExceptionHandler(sender As Object, e As UnhandledExceptionEventArgs)
        Dim ex As Exception = DirectCast(e.ExceptionObject, Exception)
        AddToLog($"UnhandledException: e.IsTerminating={CStr(e.IsTerminating)}")
        WriteException("WebCam.log", ex, "Unhandled Exception")
    End Sub

    Private Sub ReinitializeWebView()
        Controls.Remove(Me.webView)
        AddToLog("Instantiate WebView2")
        Me.webView = New Microsoft.Web.WebView2.WinForms.WebView2()
        Me.webView.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top _
            Or System.Windows.Forms.AnchorStyles.Bottom) _
            Or System.Windows.Forms.AnchorStyles.Left) _
            Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.webView.Location = New System.Drawing.Point(1, 28)
        Me.webView.Name = "webView"
        Me.webView.Size = New System.Drawing.Size(720, 426)
        Me.webView.Source = New System.Uri("about:blank", System.UriKind.Absolute)
        Me.webView.TabIndex = 0
        Me.webView.ZoomFactor = 1.0R
        Controls.Add(Me.webView)
        AddToLog("WebView2 Created")
        InitializeAsync()
        AddToLog("WebView2 Initialized")
    End Sub

    Private Sub WriteException(ByVal fileName As String, ByVal ex As Exception, ByVal exceptionSource As String)
        AddToLog(exceptionSource)
        AddToLog(ex.Message)
        Using exFile As StreamWriter = New StreamWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), fileName), True)
            exFile.WriteLine(ex.ToString)
            If Not ex.InnerException Is Nothing Then
                exFile.WriteLine(vbNewLine)
                exFile.WriteLine("InnerException:")
                exFile.WriteLine(ex.InnerException.ToString)
            End If
        End Using
    End Sub

Auto Mode Method called by Timer_Tick()

    Private Sub AutoDisplay()
        Timer.Enabled = False
        If idx = cmbWebCam.Items.Count Then
            idx = 0
        End If
        webView.Stop()
        cmbWebCam.SelectedIndex = idx
        cmbWebCam.Refresh()
        AddToLog(cmbWebCam.Items(idx))
        webView.Source = New System.Uri(cmbWebCam.Items(idx), UriKind.Absolute)
        idx += 1
        Timer.Interval = 10000
        Timer.Enabled = True
    End Sub

@mikemeinz
Copy link
Author

@pagoe-msft and @david-risney

I have continued to test by continuously running my program in Auto mode using WebView2 version 0.9.538-prelease.

After Chromium Edge Canary version 85.0.558.0 was installed, the unhandled exceptions noted in the original post no longer occurred.

Prior to Chromium Edge Canary version 85.0.558.0, there would be several unhandled exceptions each day. After Chromium Edge Canary version 85.0.558.0 was installed, there have been no exceptions thrown in more than 120 hours of continuous testing.

It looks like the Chromium Edge team has solved this issue.

I think this issue can be closed.

Thanks

@champnic
Copy link
Member

champnic commented Jul 2, 2020

Thanks @mikemeinz, we appreciate the follow-up! Closing.

@champnic champnic closed this as completed Jul 2, 2020
@champnic champnic added this to the Edge 85.0.558.0 milestone Jul 2, 2020
@kaansengul
Copy link

kaansengul commented Jan 5, 2021

I have same problem, I set Source at initialization, and leave app itself. Almost 30 mins later, it crashes:

Application: Desktop.exe CoreCLR Version: 5.0.120.57516 .NET Version: 5.0.1 Description: The process was terminated due to an unhandled exception. Exception Info: System.Runtime.InteropServices.COMException (0x8007139F): Grup veya kaynak istenen işlemi gerçekleştirmek için doğru durumda değil. (0x8007139F) at Microsoft.Web.WebView2.Core.Raw.ICoreWebView2Controller.set_IsVisible(Int32 IsVisible) at Microsoft.Web.WebView2.Core.CoreWebView2Controller.set_IsVisible(Boolean value) at Microsoft.Web.WebView2.Wpf.WebView2.UIElement_IsVisibleChanged(Object sender, DependencyPropertyChangedEventArgs e) at System.Windows.DependencyPropertyChangedEventHandler.Invoke(Object sender, DependencyPropertyChangedEventArgs e) at System.Windows.UIElement.OnIsVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) at System.Windows.UIElement.UpdateIsVisibleCache() at System.Windows.UIElement.InvalidateForceInheritPropertyOnChildren(Visual v, DependencyProperty property) at System.Windows.FrameworkElement.InvalidateForceInheritPropertyOnChildren(DependencyProperty property) at System.Windows.UIElement.OnIsVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) at System.Windows.UIElement.UpdateIsVisibleCache() at System.Windows.UIElement.InvalidateForceInheritPropertyOnChildren(Visual v, DependencyProperty property) at System.Windows.FrameworkElement.InvalidateForceInheritPropertyOnChildren(DependencyProperty property) at System.Windows.UIElement.OnIsVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) at System.Windows.UIElement.UpdateIsVisibleCache() at System.Windows.UIElement.InvalidateForceInheritPropertyOnChildren(Visual v, DependencyProperty property) at System.Windows.FrameworkElement.InvalidateForceInheritPropertyOnChildren(DependencyProperty property) at System.Windows.UIElement.OnIsVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) at System.Windows.UIElement.UpdateIsVisibleCache() at System.Windows.UIElement.InvalidateForceInheritPropertyOnChildren(Visual v, DependencyProperty property) at System.Windows.FrameworkElement.InvalidateForceInheritPropertyOnChildren(DependencyProperty property) at System.Windows.UIElement.OnIsVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) at System.Windows.UIElement.UpdateIsVisibleCache() at System.Windows.UIElement.InvalidateForceInheritPropertyOnChildren(Visual v, DependencyProperty property) at System.Windows.FrameworkElement.InvalidateForceInheritPropertyOnChildren(DependencyProperty property) at System.Windows.UIElement.OnIsVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args) at System.Windows.UIElement.UpdateIsVisibleCache() at System.Windows.PresentationSource.RootChanged(Visual oldRoot, Visual newRoot) at System.Windows.Interop.HwndSource.set_RootVisualInternal(Visual value) at System.Windows.Interop.HwndSource.set_RootVisual(Visual value) at System.Windows.Window.SourceWindowHelper.ClearRootVisual() at System.Windows.Window.CloseWindowFromWmClose() at System.Windows.Window.WmClose() at System.Windows.Window.WindowFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at System.Windows.Interop.HwndSource.PublicHooksFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(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)

MainWindow.xaml.cs:

public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); InitializeAsync(); } async void InitializeAsync() { await webView.EnsureCoreWebView2Async(); webView.Source = new Uri("_my_url.com"); } }

.NET 5 with Edge Dev 89.0.731.0

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

No branches or pull requests

5 participants