views:

984

answers:

3

Hi.

I want to make 3 threads that each run the WebBroswer control. So I would like to use the ThreadPool to make things easy.

for(int i = 0;i < 3;i++)
{
   ThreadPool.QueueUserWorkItem(new WaitCallback(gotoWork), i));
}
WaitAll(waitHandles);

....../

void gotoWork(object o)
{
   string url = String.Empty;
   int num = (int)o;
   switch(num)
   {
     case 0:
       url = "google.com";
       break;
     case 1:
       url = "yahoo.com";
       break;
     case 2:
       url = "bing.com";
       break;
   }
   WebBrowser w = new WebBrower();
   w.Navigate(url);
}

But I get an error saying that I need a STA thread which the ThreadPool will never be. Before trying this method I tried this.

Thread[] threads = Thread[3];
for(int i = 0;i < 3;i++)
{
    threads[i] = new Thread(new ParameterizedStart(gotoWork);
    threads[i] = SetApartmentState(ApartmentState.STA); //whoo hoo
    threads[i] = Start();
}
for(int i = 0; i < 3;i++)
{
    threads[i].Join();
}

And the WebBrowsers all initialized and everything looks good but only one more two will actually do anything and its never consistant at all. Threading has been such a nightmare. Can anybody suggest a nice alternative?

A: 

You need to host webbrowser control in somewhere to get it work (add it to a form), secondly you should use Invoke() of the host control (or a similar delegate) such as Form.Invoke() to interact with WebBrowser control.

No need to remind now but yes, your threads should be STA

dr. evil
A: 

Hello! You can use such type of class for your purpose to host WebBrowser control:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SomeNameSpace
{
    public class WebForm : Form
    {
        public WebBrowser WebBrowser { get; set; }

        public WebForm()
        {
            WebBrowser = new WebBrowser();
        }
    }
}
Ratamahatta
A: 

After all I choose this solution: http://watin.sourceforge.net/documentation.html

In your case you should do this:

...
Thread thread = new Thread(SomeMethod);
thread.SetApartmentState(ApartmentState.STA);
...
Ratamahatta