0

I would like to start a new thread in a for loop, then create a WebBrowser control in each thread, load a page, then do some HTML analysis. I tried to use the DocumentCompleted event, but it's never got hit. The threads seems starting properly, navigation too, but the event never fires. What's wrong with my baby?

    public async void Roller2()
    {
        for (int i = 1; i <= 1000; i++)
        {
            Thread myThread = new Thread(() => this.Wrapper(i));
            myThread.SetApartmentState(ApartmentState.STA);
            myThread.Start();
            await Task.Delay(1000);
        }
    }

    public void Wrapper(int id)
    {
        ReadAsync(id);
    }

    public void ReadAsync(int ids)
    {
        WebBrowser website = new WebBrowser();
        website.AllowNavigation = true;
        website.ScriptErrorsSuppressed = true;
        website.Navigate("http://www.someurl.com/id/" + ids.ToString());
        website.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
    }

    void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
            //Do some analysis on sender as WebBrowser
    }
dodo
  • 459
  • 2
  • 8
  • 21
  • ApartmentState.STA is a promise, cross your heart hope to die. You promise that you'll never block the thread and run a dispatcher loop. Application.Run() in .NET. You didn't, so you died, WebBrowser depends on that loop to fire the DocumentCompleted event. https://stackoverflow.com/a/4271581/17034 – Hans Passant Nov 03 '19 at 16:56
  • BTW, do make sure the web site owner allows this kind of usage. It is rare if you don't show money. They'll either throttle you, allowing only one request at time, or blacklist your IP address. – Hans Passant Nov 03 '19 at 16:59

0 Answers0