Here is a link to help explain what Sergey is trying to have you understand about what is going on with the closure capturing the
variable (not the
value!)
Captured Closure (Loop Variable) in C# 5.0 - Stack Overflow[
^]
It's interesting to note that, since C# 5.0 switching the
for (int i = 0; i < elc.Count - 1; ++i)
{
HtmlElement element = null;
this.Invoke((MethodInvoker)delegate
{
element = elc[i];
});
to be
foreach (HtmlElement element in elc)
{
solves both the captured variable and indexing errors!
(This only barely qualifies as a "Solution", but there's no good way to markup code in a comment.)
===========
Edit Apr 11, 2016 -- MTH:
Since the collection is getting changed out from under you at inopportune times, you need to get
a copy of the collection in a safer way.
(This is all in addition to Sergey's comments suggesting that you need to rethink the strategy in general!)
Running the check in the UI thread
should prevent the collection from being changed while a checking "pass through the collection" is in progress.
public void StartFunction()
{
bool Connected = false;
Action connectedCheck = () => {
Connected = webBrowser1.Document.Body.All.Cast<HtmlElement>().Any(el =>
{
bool conn = false;
if (el != null)
{
string inner = el.InnerHtml;
if (inner != null)
conn = inner.StartsWith("connected");
}
return conn;
});
};
while (true)
{
webBrowser1.Invoke(connectedCheck);
if (Connected)
return;
}
}