0
 private void checkProxies()
        {
            foreach(string x in proxyList)
            {
                Task<bool> task = CheckProxy.CheckProxyNonBlocking(x);
                Application.DoEvents();
                task.ContinueWith((t) =>
                {
                    if (!t.Result)
                        Application.DoEvents();
                    else
                    {
                        this.Invoke((MethodInvoker)delegate
                        {
                            validTextBox.Text += x + "\n";
                        });
                    }
                });
            }
        }

I'm trying to build a proxy checker with a multi-threaded design ,proxyList is a variable from the type of 'string[]'.

My question is , if the checking takes a lot of time, is the x I am passing to the function checkProxyNonBlocking is the same x I'm dealing with in continue with?

NotGI
  • 458
  • 9
  • 21

1 Answers1

0

If you are using C# 5 (or later) and a foreach loop then it should work the way you expect, and validTextBox.Text += x + "\n" will have the correct value of x for that loop iteration. However if you are using C# 4 or a for loop then you will get inconsistent results where x might (depending on timing) have a value from a later loop iteration.

For a full explanation, read Access to foreach variable in closure warning and Closing over the loop variable considered harmful.

Community
  • 1
  • 1
Jared Moore
  • 3,765
  • 26
  • 31
  • Only 2 of those tasks are really getting executed , do you have any idea why? – NotGI Jul 09 '15 at 20:38
  • It looks like you aren't explicitly waiting for the tasks to complete. Is it possible that your app or test exists while the tasks are still running? – Jared Moore Jul 09 '15 at 21:33
  • Yeah I just want to add it to the list once checking is done. – NotGI Jul 10 '15 at 15:56