The problem I'm facing is that, when dealing with the WebBrowser
control (whether it's visible or not), it causes the UI to freeze for a small amount of time while navigating, which becomes very noticeable and unreliable when having to open several URLs sequentially.
I'm currently using Noseratio's NavigateAsync
extension method to navigate to multiple URLs silently & asynchronously: (Feel free to skip reading the code and continue with the question)
public static async Task<string> NavigateAsync(this WebBrowser webBrowser, string url, CancellationToken token)
{
var tcs = new TaskCompletionSource<bool>();
WebBrowserDocumentCompletedEventHandler handler = (s, arg) => tcs.TrySetResult(true);
using (token.Register(() => { webBrowser.Stop(); tcs.TrySetCanceled(); }, true))
{
webBrowser.DocumentCompleted += handler;
try
{
webBrowser.Navigate(url);
await tcs.Task; // wait for DocumentCompleted
}
finally
{
webBrowser.DocumentCompleted -= handler;
}
}
var documentElement = webBrowser.Document.GetElementsByTagName("html")[0];
var html = documentElement.OuterHtml;
while (true)
{
await Task.Delay(POLL_DELAY, token);
if (webBrowser.IsBusy)
continue;
var htmlNow = documentElement.OuterHtml;
if (html == htmlNow) break;
html = htmlNow;
}
token.ThrowIfCancellationRequested();
return html;
}
But even the simplest code like the following:
WebBrowser wb = new WebBrowser() { ScriptErrorsSuppressed = true };
wb.Navigate("https://www.google.com/");
..still has the same effect.
Here's a quick demo video showing the problem with the simplest code possible.
I also tried having the WebBrowser running on a different STA thread, but still no luck.
So, is there a way to avoid that freeze while dealing with WebBrowser
?
Before you bother to suggest replacing it with HttpClient
or WebClient
with HTMLAgilityPack
, please note that I'm using WebBrowser in order to get the displayed text, formatted as close as possible to how it's displayed in the browser (i.e., as close as possible to manually selecting & copying the text). Every solution I tried (or found online) without using a browser failed to achieve this, even the one that produced the closest result wasn't good enough.