I am writing a C# application that will be loading a technical chart webpage that is generated by an outside server API. I am just trying to display a webpage that i would like to be loaded in a custom panel using WebView2 (as original WebBrowser is deprecated, and Cef has x64 problems).
However, the following code fails to execute properly and is throwing a com exception, when attempting to initialize the custom view:
class ChartView : Panel
{
#nullable enable
private string? chartViewFileAddr { get; set; }
#nullable disable
private WebView2 chartWebView { get; set; }
private async void ensureWeb2Init() => await chartWebView.EnsureCoreWebView2Async(null);
private bool isInit = false;
public ChartView(string? chartViewFileAddr) : base()
{
this.chartViewFileAddr= chartViewFileAddr ?? "";
this.BorderStyle = BorderStyle.Fixed3D;
this.Size = new System.Drawing.Size(300, 500);
this.Location = new Point(0, 320);
this.Name = "ChartWebView";
chartWebView= new WebView2();
chartWebView.Size = this.Size;
chartWebView.Location = new System.Drawing.Point(0, 0);
if (isInit == false)
{
Task.Run(() => this.ensureWeb2Init()).Wait();
isInit = true;
}
chartWebView.CoreWebView2.Navigate("google.com"); //base address for testing
this.Controls.Add(chartWebView);
}
}
When it runs, it fails on calling ensureWeb2Init. If i attempt to run the task without the Wait function, it fails to run asynchronously, if i add the wait function, the async task throws the following:
System.Runtime.InteropServices.COMException: 'Cannot change thread mode after it is set. (0x80010106 (RPC_E_CHANGED_MODE))'
For whatever reason, i cannot get the WebView2 to initialize properly. Is there anything i am doing wrong here? thank you for your help.