I have a winforms form that instantiates a ChromiumWebBrowser instance in it's constructor, when the form is initialized. I have a FormClosing() function that runs whenever the form closes both from clicking the "x" button, and when calling .Close(). When I close the form using the "x" button, i'm able to dispose the Browser object without an issue, in the FormClosing method. However, if I call .Close() on the form, when I .Dispose() line is hit in FormClosing() on that same Browser object, my app freezes for about 30 seconds, leading me to believe the Browser object is on a different thread.
However, if I check .InvokeRequired on the Browser object, it returns false. How can I dispose of the ChromiumWebBrowser instance without causing the app to freeze? Why does .Dispose() work fine when clicking the "x" button?
Here is my constructor:
public PhxCEFBrowser(string url)
{
InitializeComponent();
Browser = new ChromiumWebBrowser(url)
{
Dock = DockStyle.Fill,
Location = new Point(0, 0),
MinimumSize = new Size(20, 20),
Name = "webBrowser1",
Size = new Size(284, 261),
TabIndex = 0,
};
Browser.BrowserSettings.ApplicationCacheDisabled = true;
Browser.KeyboardHandler = new KeyboardHandler();
browserPanel.Controls.Add(Browser);
ClientSize = new Size(284, 261);
Name = "WebBrowser";
ResumeLayout(false);
}
And here is my FormClosing() handler:
private void PhxCEFBrowser_FormClosing(object sender, FormClosingEventArgs e)
{
browserPanel.Controls.Remove(Browser);
if (Browser.InvokeRequired)//<-- Returns false
{
Browser.Invoke(new MethodInvoker(delegate
{
Browser.Dispose();//<-- never gets hit
}));
}
else
{
Browser.Dispose();//<-- gets hit when calling .Close(), causing the app to freeze. works fine without freezing when clicking the "x" button
}
}