2
votes

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 !

2
What is AddSerie, and what does it do? - SWeko
Does AddSerie perhaps add an entry to IndexSeries? - Joey
It does not matter here, There is just one record and I expect that method to be executed just once, this foreach loop why is continuing endlessly ? - Kasrak
@user1096... reaching an OutOfMemory exception is hard if you do small allocations, have a 64-bit OS and a lot of disk space. - zmbq
var list = new List<int> { 1 }; list.ForEach(i => list.Add(i)); //hits out of memory in a second on a 64bit os and machine with 3gb memory - user1096188

2 Answers

4
votes

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.

2
votes

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 :)