Kasrak
Kasrak

Reputation: 1561

ForEach loop for a Generic List repeated endlessly

After Deserializing a file with just one record

It seems that it's in an infinitive loop

IndexSeries = (List<string>)bFormatter.Deserialize(fsSeriesIndexGet);
IndexSeries.ForEach(name => AddSerie(name));
//IndexSeries.ForEach(delegate(String name)
//{
      //    AddSerie(name);
//});

AddSerie will be executed infinitively !

Upvotes: 2

Views: 1548

Answers (2)

SWeko
SWeko

Reputation: 30902

If I define:

//class level declaration (in a console app)
static List<string> strings;

static void Loop(string s)
{
  Console.WriteLine(s);
  strings.Add(s + "!");
}

Then

static void Main(string[] args)
{
  strings = new List<string> { "sample" };
  strings.ForEach(s => Console.WriteLine(s));
}

executes normally, outputing a single string, while

static void Main(string[] args)
{
  strings = new List<string> { "sample" };
  strings.ForEach(s => Loop(s));
}

loops indefinitely, adding '!'s in the process, and

static void Main(string[] args)
{
  strings = new List<string> { "sample" };
  foreach (string s in strings)
  {
    Loop(s);
  }
}

throws an InvalidOperationException (Collection was modified; enumeration operation may not execute), which, in my opinion is the correct behavior. Why the List.ForEach method allows the list to be changed by the action, I do not know, but would like to find out :)

Upvotes: 2

Grant Thomas
Grant Thomas

Reputation: 45083

You use ambiguous terms. Firstly you mention an infinite loop, and then mention that AddSerie will be executed 'infinitively' [sic]; based on this, I would think that the issue you're bringing up is not with ForEach going on and on forever (as implied/stated), but instead that AddSerie does something once that seems to be taking forever.

This could even amount to something mentioned by Joey: if you're adding an element to a list while within the context of a ForEach call, then you're always one step behind in completion, and hence won't 'complete'. However, getting an OutOfMemoryException would actually occur relatively quickly if, say, AddSerie does nothing but that - it might take longer to get to such a point if AddSerie is a relatively time-consuming method. Then again, you might never get such an exception (in the context discussed) if AddSerie simply takes a dogs age to complete without contributing to the length of the list.

Showing your AddSerie code would be potentially most helpful in determining the actual issue.

Upvotes: 4

Related Questions