g.foley
g.foley

Reputation: 2172

Using WebBrowser control in class library

I'm trying to use this control inside a class library, but when I run the code below, I did not see a request to google being sent (using fiddler).

public class WebBrowserTest
{
    public WebBrowserTest()
    {
        var t = new Thread(StartBrowser);
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
    }

    private void StartBrowser()
    {
        WebBrowser web;
        web = new WebBrowser();
        web.Navigate("http://www.google.com");
    }
}

My guess is this has something to do with threading, and possibly the thread ending before the control gets a chance to send the request. But I have no idea where to start with solving this.

THE SOLUTION

I found this solution to work, the events are getting fired and the main thread waits for the STA thread.

public class WebThread
{
    private WebBrowser web { get; set; }

    public void StartBrowser()
    {
        web = new WebBrowser();
        web.Visible = true;
        web.DocumentCompleted += Web_DocumentCompleted;
        web.ScriptErrorsSuppressed = true;
        web.Navigate("http://www.google.com");

        Application.Run();

        web.Dispose();
    }

    private void Web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        Debug.Print("Arrived: " + e.Url.ToString());

        if (e.Url.ToString() == "http://www.google.com.au/")
        {
            Application.ExitThread();
        }
    }
}


public class WebBrowserTest
{
    public WebBrowserTest()
    {
        Debug.Print("Thread is starting.");
        var webThread = new WebThread();

        var t = new Thread(webThread.StartBrowser);
        t.SetApartmentState(ApartmentState.STA);
        t.Start();

        while(t.IsAlive)
        {
            Thread.Sleep(5000);
        }

        Debug.Print("Thread has finished.");
    }
}

Upvotes: 1

Views: 5687

Answers (1)

Nick Butler
Nick Butler

Reputation: 24383

WebBrowser.Navigate( ... ) doesn't block - it returns immediately, before the request is sent. Since your thread function then exits, your whole thread ends and takes your WebBrowser control with it.

If you're just trying to download a web page, have a look at the WebClient class. It has many async methods which means you probably won't even have to create your own thread.

Upvotes: 2

Related Questions