Im building a program that surf to several websites and do something.
After surfing to like 5 urls successfully, the program hangs after the Application.Run() line. The program doesn't even enter the Handler function and just stuck. the CPU usage is 0 at this point.
I tried closing the threads in any possible way. What i'm doing wrong?
I'm doing it like that:
[STAThread]
private static void Main(string[] args)
{
for (int i = 0; i < urls.Count; i++)
{
var th = new Thread(() = >
{
var weBrowser = new WebBrowser();
weBrowser.AllowNavigation = true;
weBrowser.DocumentCompleted += Handler;
weBrowser.Navigate(urls[i]);
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join();
}
}
And my Handle function is:
private static void Handler(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser weBrowser = sender as WebBrowser;
var htmlDocument = weBrowser.Document;
/*do something*/
Application.Exit();
Application.ExitThread();
weBrowser.Dispose();
weBrowser.Stop();
Thread.CurrentThread.Abort();
}
My problem is very similar to this one: Application.Run() leads to application hanging
There is no answer in this question either.
Thanks!
I think you are doing several mistakes:
Application.Exit()
in each handler callYou should move the joining outside the for loop and do not call Application.Exit
.
The following sample seems to work well:
static class Program
{
[STAThread]
static void Main()
{
var urls = new List<string>() {
"http://stackoverflow.com",
"http://stackoverflow.com",
"http://stackoverflow.com",
"http://stackoverflow.com",
"http://stackoverflow.com",
"http://stackoverflow.com",
"http://stackoverflow.com",
"http://stackoverflow.com"};
var threads = new Thread[urls.Count];
for (int i = 0; i < urls.Count; i++)
{
threads[i] = new Thread((url) =>
{
var weBrowser = new WebBrowser();
weBrowser.AllowNavigation = true;
weBrowser.DocumentCompleted += Handler;
weBrowser.Navigate(url as string);
Application.Run();
});
threads[i].SetApartmentState(ApartmentState.STA);
threads[i].Start(urls[i]);
}
foreach (var t in threads)
t.Join();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
private static void Handler(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser weBrowser = sender as WebBrowser;
var htmlDocument = weBrowser.Document;
/*do something*/
Application.ExitThread();
weBrowser.Dispose();
weBrowser.Stop();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With