Search code examples
c#wpfc++-cli

Opening a WPF Window from C++/CLI via async method is blocking


I am attempting to open a WPF Window that contains a WebView2 control so I can add OpenID Connect authentication to an existing C++ CLI application.

We are using https://github.com/IdentityModel/IdentityModel.OidcClient.Samples/tree/main/WpfWebView2/WpfWebView2 as the basis of our code.

If you are not familiar with this sample, the idea behind it is there a "custom" class that represents the "browser". This class is responsible for instantiating the WPF Window, adding a WebView2 control as its content, navigating to the OAuth site, and returning the auth results to the caller. All of this happens when its InvokeAsync() method is called.

What calls this async method is the OidcClient class from the IdentityModel.OidcClient library. The OidcClient class takes in a settings class, one of which is the class that implements its IBrowser interface. You kick off this authentication logic by calling OidcClient.LoginAsync from your application. In my case, this is the C++ code.

When I call LoginAsync() from my C++ code, the app blocks and the window does not open. I am pretty sure that this is a UI thread issue but for the life of me I cannot figure it out.

I have attempt a number of approaches including trying to wrap calls in Application.Current.Dispatcher.Invoke() and Application.Current.Dispatcher.BeginInvoke(). I have tried detecting if I was on the UI thread so I can create a DispatcherSynchronizationContext.

I suspect the issue is the async/await call from C++ that starts with non-UI work and at some point needs to do the UI work. From C++, I can easily create instances of WPF Window (via gcnew) and then call Show() or ShowDialog() but this multiple layer async/await design is causing problems.

I am using LoginAsync().Wait() from the C++ side so it is very possible that this is simply a matter of not calling the async method from C++ correctly. I am not even sure where else to look or what additional knowledge I need to debug this specific set up.


Solution

  • The call to .Wait() pretty sure causes deadlock.

    If you don't need a result from LoginAsync immediately, register continuation using .ContinueWith(...) instead.

    If you need a result from LoginAsync synchronically then start a new DispatcherFrame in UI thread. C# code would look like this:

    // Assuming that the 't' is a Task<...>.
    var t = LoginAsync();
    
    var frame = new DispatcherFrame();
    t.ContinueWith((_) => { frame.Continue = false; }, TaskContinuationOptions.ExecuteSynchronously);
    
    // Block current thread until LoginAsync is completed, while performing all UI stuff.
    // (Make sure you call this in UI thread)
    Dispatcher.PushFrame(frame);
    
    // Since 't' is already completed, this call won't block the thread.
    var loginResult = t.Result;