ExecuteScriptAsync().Result 从不 return

ExecuteScriptAsync().Result never return

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

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

上面的代码,第一行之后就不会继续了,所以无法得到javascript的结果。

但是对于这些代码:

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

它 return 立即响应 1 = "1"

我想知道为什么。

异步函数被特殊类型包装(在 JS 中称为 Promise,在 C# 中称为 Task)。 当您需要获得结果时,您应该使用关键字 await 来等待函数结束 运行 和 'unwrap' 结果

WebView2 threading documentation讲到这个。 TLDR WebView2 依赖于 UI 线程消息泵并且 Task.Result 阻止了它。

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.