MicrosoftEdge / WebView2Feedback

Feedback and discussions about Microsoft Edge WebView2
https://aka.ms/webview2
444 stars 53 forks source link

COMException 0x8007139F calling EnsureCoreWebView2Async #2495

Closed coonmoo closed 1 year ago

coonmoo commented 2 years ago

Description

Running the attached sample results in an COMException after the application was forcefully killed and executed again.

Version SDK: 1.0.721 (1.0.1210.39) Runtime: 102.0.1245.33 Framework: WPF net472 (.NET 6) OS: 10.0.22000 Build 22000

Exception

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=mscorlib
  StackTrace:
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at Microsoft.Web.WebView2.Core.CoreWebView2Environment.<CreateCoreWebView2ControllerAsync>d__68.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Web.WebView2.Wpf.WebView2.<>c__DisplayClass27_0.<<EnsureCoreWebView2Async>g__Init|0>d.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at WpfApp1.MainWindow.<InitializeAsync>d__9.MoveNext() in C:\Users\user\Downloads\WpfWebView2Playground-master\WpfApp1\MainWindow.xaml.cs:line 73

  This exception was originally thrown at this call stack:
    [External Code]
    WpfApp1.MainWindow.InitializeAsync() in MainWindow.xaml.cs

Repro Steps

  1. Clone https://github.com/RickStrahl/WpfWebView2Playground
  2. Run Debug
  3. Kill application
  4. Run Debug again
  5. Resulting in Exception

Additonal notes I updated the SDK to 1.0.1210.39 resulting in the same issue. I updated to .NET 6 resulting in the same issue.

coonmoo commented 2 years ago

I was able to workaround the issue by copying the FixedRuntime to a temporary folder on each application startup.

var runtimeSource = @"C:\runtimes\source\Microsoft.WebView2.FixedVersionRuntime.102.0.1245.33.x64";
// Copy runtime to a temp folder
var tempRunTimeFolder = Path.Combine(@"C:\runtimes\temp", Guid.NewGuid().ToString());        
CopyDirectoryRecursive(runtimeSource, tempRunTimeFolder);

var env = await CoreWebView2Environment.CreateAsync(tempRunTimeFolder);
await webView.EnsureCoreWebView2Async(_env);

Note: I'm getting the COMException also in a fresh project basically doing nothing besides loading the webview2 with the source pointed to "https://google.com". As soon as the app quits forcefully subsequent starts will fail with the exception.

The only working solution I found is to copy the runtime on each start to a fresh directory.

david-risney commented 2 years ago

When you kill the host app process, the webview2 processes will clean themselves up and shutdown. If you restart your app, and the app tries to create a WebView2 while the previous webview2 processes are shutting down you can get this exception. If creation fails in this manner you can try waiting a bit and then retrying webview2 creation.

If you change the runtime folder or the user data folder then webview2 creation may not try to connect to the same existing webview2 processes that are shutting down.

coonmoo commented 2 years ago

@david-risney not sure if that's the issue I'm seeing. I waited a pretty long time and still seeing the same exception. I even restarted my computer and get the same exception after starting the app again.

The only thing which seems to help to "repair" the webview2 is to copy the runtime to a different folder.

david-risney commented 2 years ago

You might check what msedgewebview2.exe processes running before and after you enter this state. Perhaps you're hitting an issue where the msedgewebview2.exe process is still running but somehow stuck trying to shutdown.

Also, do you share your user data folder with any other processes?

coonmoo commented 2 years ago

@david-risney like I stated the issue persists even after restarting windows. There are no msedgewebview2 processes running.

The user data folder is not shared, every time the Wpf application is started there is a new random temp folder as the userDataFolder provided.

coonmoo commented 2 years ago

I'm getting the same exception when using the shared runtime.

await webView.EnsureCoreWebView2Async();

The first app start (after a system reboot) works fine. All subsequent launches result in the originally mentioned exception.

coonmoo commented 2 years ago

I checked the registry keys mentioned here and did not find any of the mentioned registry keys present on my system.

Runtime is installed though. I "repaired" the runtime without any luck.

image
gauthier-scano commented 2 years ago

Hello,

I have the same problem than coonmoo. Every time I run my solution (in debug or release), an exception is throwed on line await webView.EnsureCoreWebView2Async(); => COMException : Le groupe ou la ressource n’est pas dans l’état correct pour effectuer l’opération requise. (Exception de HRESULT : 0x8007139F (FR version)

Tries Here is what I tried, any of them do not work:

await webView.EnsureCoreWebView2Async(env); <= Kaboom


- Change WebView2 default page location
- Repair Visual Studio (using 2019 community edition)
- Install Visual Studio 2022 (community edition)
- Delete all the temp files and directories from C:/Users/[USER]/AppData/Local/Temp
- Try my project on an other Windows 11 computer (opening project + executing .exe from VisualStudio Release directory) **and it works there**
- Try to run an empty project just with an empty WebView2 => same problem
- Try to run a demo project from https://github.com/RickStrahl/WpfWebView2Playground => same problem, so it seems that the problem does not depend on the code (which do not contain any error or misuse of WebView2).
- Try to run directly the .exe from Release directory does not work

**Notes**
1) Last week, my computer was off during 4 days and when I start my computer today, WebView2 worked 3/4 times then the same exception appeared again. **So it seems that it's a cache problem.**
2) All my other projects using WebView2 do not work anymore but they all worked like a charm before. (Some of them are currently in production on others W10/11 computers). **So it seems that the problem do not depend on the VS project or the directory environnement used by the WebView (which change every time project is run).**
3) No process msedgewebview2.exe is running on my computer when I try to run my soft. **So there is no concurrent access problem.**
4) All processes can access to this directory (it's managed by Windows). **So it's not an access right problem.**

**Version**
WebView2 Runtime: 103.0.1264.62
Framework: WPF .NET 4.7.2
OS: Windows 11 Version 21H2 (build 22000.795)

I have numerous project using this technology than I need to code. Can someone provide any help about this exception ?

Thanks a lot !

**Error detail**

System.Reflection.TargetInvocationException HResult=0x80131604 Message=Une exception a été levée par la cible d'un appel. Source=mscorlib Arborescence des appels de procédure : at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) at System.Delegate.DynamicInvokeImpl(Object[] args) at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme) at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme) at System.Windows.Forms.Control.InvokeMarshaledCallbacks() 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.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at IntegraMeteringUpdater.Program.Main()

Cette exception a été levée à l'origine dans cette pile des appels : [Code externe]

Exception interne 1 : COMException : Le groupe ou la ressource n’est pas dans l’état correct pour effectuer l’opération requise. (Exception de HRESULT : 0x8007139F)

rvoelkel-nest commented 2 years ago

My customer has the same problem. Worked like a charm, next day WebView2 stopped working.

WebView2 Runtime (Fixed Version): 95.0.1020.53 Framework: .NET Core 3.1 with WPF OS: Windows 10

We noticed that Microsoft rolled out WebView2 Runtime for Windows 10.

david-risney commented 2 years ago

When you run under the debugger, if you look at the Debug Output, do you see any WebView2 related messages?

rvoelkel-nest commented 2 years ago

Can't run in debugger mode, because my customer uses the released software and I don't have this bug.

Only WebView2 related message I have is MicrosoftTeams-image

jairbubbles commented 2 years ago

Hey all, I have a similar issue that happens when I update the WebView2 package in my application.

After reading this thread I considered that it might a cache issue so I try to override the user data folder:

Environment.SetEnvironmentVariable("WEBVIEW2_USER_DATA_FOLDER",  <custom_user_folder>);

And it's working! I'll make more tests and add the results in this thread.

ErikSkaarup commented 1 year ago

I can replicate the same issue, by loading a Word JS Add in (e.g Wikipedia) and open the add in and then in my case activate a VSTO addin which requires webview2.

image

By removing the Wikipedia addin everything works

Word JS addin uses WebView2 now as the default HTML browser there is a conflict, @jairbubbles suggestion is not working in this case.

VSTO using WPF, .net 4.8 and using Microsoft.Web.Webview2 version 1.0.1245.22

SvenEV-bakerhughes commented 1 year ago

I encountered the same issue with a .NET 6 WinForms app with WebView2. In my case it seems to be related to high DPI settings: I enabled per-monitor high DPI rendering through <ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode> and then tried to launch one instance of the app with this setting and one without it to compare them side-by-side. The second launch fails with COMException 0x8007139F.

I can easily launch multiple instances of the app as long as either all or none have the PerMonitorV2 scaling enabled. But as soon as I launch an instance where the scaling setting deviates from those of the already running processes, the error occurs.

JonathanHart-CIS commented 1 year ago

I encountered the same issue with a .NET 6 WinForms app with WebView2. In my case it seems to be related to high DPI settings: I enabled per-monitor high DPI rendering through <ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode> and then tried to launch one instance of the app with this setting and one without it to compare them side-by-side. The second launch fails with COMException 0x8007139F.

I can easily launch multiple instances of the app as long as either all or none have the PerMonitorV2 scaling enabled. But as soon as I launch an instance where the scaling setting deviates from those of the already running processes, the error occurs.

Thank you SvenEV-bakerhug! I had the same issue and this solved it for me too!!

breyed commented 1 year ago

The Disable display scaling on high DPI settings compatibility setting works around this issue.

thiago-souza-mx commented 1 year ago

Realizar os procedimentos descritos neste site funcionou para mim. https://support.templafy.com/hc/en-us/articles/10510746266525-How-to-repair-Webview2-Runtime

novac42 commented 1 year ago

Closing the issue as it's by design if there're mismatched DPI awareness values (or mismatched other environment options) when connecting to an already running environment, or trying to connect to a runtime environment that is already shutting down. The error can be avoided by adjusting high DPI setting as mentioned in comments above.