-1
var response2 = webView21.CoreWebView2.ExecuteScriptAsync("function foo(){return 1;}; foo();").Result;

if (response2 != null) //it never reach here
{
     //...
}

For the code above, it will not continue after the first line, so I can't get the result of the javascript.

But for these codes:

string response1 = await webView21.CoreWebView2.ExecuteScriptAsync(
    "function foo(){return 1;}; foo();"
);

It return immediately with response1 = "1"

I am wondering why.

camino
  • 10,085
  • 20
  • 64
  • 115

2 Answers2

2

The WebView2 threading documentation talks about this. TLDR WebView2 relies on the UI thread message pump and Task.Result blocks that.

WebView2 relies on the message pump of the UI thread to run event handler callbacks and async method completion callbacks. If you use methods that block the message pump, such as Task.Result or WaitForSingleObject, then your WebView2 event handlers and async-method completion handlers don't run. For example, the following code doesn't complete, because Task.Result stops the message pump while it waits for ExecuteScriptAsync to complete. Because the message pump is blocked, the ExecuteScriptAsync isn't able to complete.

David Risney
  • 3,886
  • 15
  • 16
1

An async function is wrapped by a special type (in JS it's called Promise, in C# - Task). When you need to get the result you should use with keyword await to wait for the end of the function run and 'unwrap' the result