Possible Duplicate:
WebBrowser Control in a new thread
I’m trying to automate clicking certain element on a webpage that then spawn a new IE window on each click.
The code below reads a DataTable with one column containing the element IDs I need to click. It then cycles the table and clicks the required element in the Webbrowser webNav.webBrowser1.
The code works fine the first time it runs but thereafter there are no more click events. If I step through using breakpoints then I can see the code is running fine without a problem. It appears as if it’s scheduling the actions which never get triggered.
This is my first time attempting to use threads so I might be doing something fundamentally wrong.
At the moment I’m a bit stumped as to what the problem is?
[STAThread]
private void ClickOptions()
{
DataTable _dataTableTestClone = new DataTable();
_dataTableTestClone = _dataTableTest;
if (_dataTableTest != null)
{
var thread = new Thread(() =>
{
foreach (DataRow row in _dataTableTestClone.Rows)
{
string getclickID = row["ID"].ToString();
webNav.webBrowser1.Invoke(new Action(() =>
{
HtmlElement lit = webNav.webBrowser1.Document.GetElementById(getclickID);
if (lit != null)
{
lit.InvokeMember("click");
}
}));
Thread.Sleep(2000);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
}
}
Why are you setting the thread apartment state to STA? I don’t think it has any purpose. Only the thread you use to create controls or interact with certain COM objects needs to be STA (which isn’t the thread you are starting there, as the Invoke() call on webBrowser1 will marshal your action to the UI thread).
You can try wrapping the code on the inside of your Invoke with try/catch and adding a breakpoint to something on the inside of the catch block to see if any exceptions pop up, as exceptions in multithreaded scenarios sometimes act a little funny depending on how the rest of your application is setup. I’m willing to bet you are getting an exception that is being swallowed somewhere.
EDIT: if the only purpose to your thread is to have a 2 second delay between invoked actions, I would use System.Windows.Forms.Timer instead:
http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx