I have multi-threaded WinForms app, with several threads working with WebBrowser
. Here is a part of my code (just a start of the function)
private void createThreads()
{
int i = 1;
foreach (Account acc in Accounts)
{
Thread buyer = new Thread(() => Buy(acc, i)) { ApartmentState = ApartmentState.STA };
i++;
buyer.Start();
Buyers.Add(buyer);
}
}
private void Buy(Account ac, int id)
{
WebBrowser browser = new WebBrowser();
browser.ScriptErrorsSuppressed = true;
Account acc = new Account();
acc.username = ac.username.ToString();
acc.password = ac.password.ToString();
acc.shoes = ac.shoes.ToList();
while (run)
{
if(acc.shoes == null || acc.shoes.Count < 1){return;}
Product toBuy = acc.shoes[0];
browser.Navigate(toBuy.url);
while (browser.Document == null) { Thread.Sleep(25); } //wait for the document to download (at least some data received)
while (browser.Document.Body == null) { Thread.Sleep(25); } //wait for at least some body to download
Now, the thread never leaves the first while
loop, the document is always null. Earlier, I run this in one thread, and instead of Thread.Sleep()
I called Application.DoEvents()
(as advised in another question here on SO) and it worked fine. However, that seemed to cause AccessViolationException
when run on multiple threads, so I changed to Thread.Sleep()
here and I call Application.DoEvent()
in a Windows.Forms.Timer
in the main app thread, called each milliseconds.
Any idea why the browser doesn't load anything and how to fix this?
Aucun commentaire:
Enregistrer un commentaire