0

This code gives exception: System.ArgumentOutOfRangeException

ArrayList conarr = new ArrayList();

conarr.Add("User ID=sysdba;Password=wrongpass1;" +
 "Database=C:\\prod\\file.fdb;DataSource=192.168.0.5;Charset=NONE; Connection Timeout=30;Pooling=false;");

conarr.Add("User ID=sysdba;Password=wrongpass2;" +
 "Database=C:\\prod\\file.fdb;DataSource=192.168.0.5;Charset=NONE; Connection Timeout=30;Pooling=false;");

conarr.Add("User ID=sysdba;Password=GOODPASS;" +
 "Database=C:\\prod\\file.fdb;DataSource=192.168.0.5;Charset=NONE; Connection Timeout=30;Pooling=false;");


for (int t = 0; t < conarr.Count; t++)
{  
    Thread tr = new Thread(delegate() 
    {
        trycon(conarr[t].ToString()); //<---------
    });

    tr.Start();
}

but if i change this thread creation to:

for (int t = 0; t < conarr.Count; t++)
{
    string cs = conarr[t].ToString(); //<------

    Thread tr = new Thread(delegate ()
    {
        trycon(cs); //<-------
    });
    tr.Start();
}

than it works fine. Why? (this code is for searching which connection to database is good and which one is wrong, in separate parallel threads )

Diego Rafael Souza
  • 5,060
  • 3
  • 21
  • 56
user2265690
  • 129
  • 6
  • 2
    Basically, in the first form you're capturing the variable `t`, which is a *single* variable whose value changes over time. In the second form you're capturing the `cs` variable *for that iteration of the loop*. As an aside, I'd strongly encourage you to use generic collections, lambda expressions, and potentially other ways of achieving parallelism (e.g. tasks). – Jon Skeet Apr 03 '18 at 12:11
  • 1
    You're closing over the loop variable `t`. A good explanation of why this creates problems can be found in [Eric Lippert's blog post](https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop-variable-considered-harmful/). And unrelated, consider using `List` insead of `ArrayList`. – Dirk Apr 03 '18 at 12:12
  • 1
    (There are lots of questions that are *like* this, but I don't have time to search for an exact duplicate right now.) – Jon Skeet Apr 03 '18 at 12:12
  • 1
    This is likely due to [closing over the loop variable](https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop-variable-considered-harmful/). Your first sample will probably get the same value of `t` several times. To fix it, assign it to a temporary variable before passing the temp to the thread. – Matthew Watson Apr 03 '18 at 12:13
  • 1
    Another similar question: https://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp – default locale Apr 03 '18 at 12:15

0 Answers0