7 Replies - 8283 Views - Last Post: 08 February 2012 - 08:44 PM Rate Topic: -----

#1 SilverAstrid  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 16-January 10

Infinite Loop in c# foreach

Posted 08 February 2012 - 03:38 PM

List<LBStatsData> list = new List<LBStatsData>();
            foreach (var dateTimeGroup in things)
            {
               //Console.WriteLine("DateGroup");
                //Console.WriteLine(dateTimeGroup.Value.ElementAt(0).StartsWith("[main/main] status report"));
                if (dateTimeGroup.Value.ElementAt(0).StartsWith("[main/main] status report"))
                {
                    LBStatsData data = new LBStatsData();

                    foreach (string s in dateTimeGroup.Value)
                    {
                       // Console.WriteLine(s);
                        StatGroup group = new StatGroup();
                        string[] split = s.Split(':');
                        group.Name = split[0];
                        StatusCollection collection = new StatusCollection(split[1].Substring(1));
                        KeyValuePair<string, ulong> pair = new KeyValuePair<string, ulong>();
                        foreach (string statKey in collection.Keys)
                        {
                            ulong val = 0;
                            //Console.WriteLine("try get {0}: {1}",statKey, collection.TryGetStat(statKey, out val));
                            if (collection.TryGetStat(statKey, out val))
                            {

                                pair = new KeyValuePair<string, ulong>(statKey, val);
                                group.Stats.Add(pair);

                            }
                        }
                        
                        data.Groups.Add(group);
                        //Console.ReadLine();
                    }
                    //Console.WriteLine();
                    list.Add(data);
                }
            }



Couple of things. I know that adding to a collection while iterating on it can cause this... but I don't think I'm doing it. I also read somewhere that if your code throws an exception it can get caught? That doesn't sound right to me, but this code is sort of throwing an exception. The collection.TryGetStat method has parsing code that simply has
try
{
     intValue = Convert.ToUInt64(intText);
}
catch
{
     return false;
}
could that be it?

Thanks so much for your help!



Is This A Good Question/Topic? 0
  • +

Replies To: Infinite Loop in c# foreach

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5677
  • View blog
  • Posts: 12,209
  • Joined: 02-June 10

Re: Infinite Loop in c# foreach

Posted 08 February 2012 - 03:47 PM

SilverAstrid What this shows us is that you aren't familiar with breakpoints and how to debug your own code.Learning to debug one's own code is an essential skill. Sadly, one that apparently no college course teaches. Silly if you ask me.

Placing breakpoints and walking through the code line by line allows you to actually WATCH it execute. Visualizing what your code does will let you see why it behaves the way it does.

It would be well worth your time to do the tutorials on FAQ 2. A couple hours learning this skill will save you hundreds of hours of confusion in one project alone.

TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Form1 talk to Form2



FAQ (Frequently Asked Questions - Updated Jan 2012

Spoiler


Quote

I also read somewhere that if your code throws an exception it can get caught? That doesn't sound right to me,


Why doesn't that sound right? You do it in your example:
try
{
     intValue = Convert.ToUInt64(intText);
}
catch
{
     return false;
}



A foreach simply cannot become an infinate loop because collections are not infinite. That have a defined set of values.

Of course if you have methodA, that calls methodB, that calls methodA... now you have a circular reference that will eventually overflow the stack and cause a stackoverflow exception.

So why is you think you have an infinte loop going on here?

This post has been edited by tlhIn`toq: 08 February 2012 - 03:42 PM

Was This Post Helpful? 0
  • +
  • -

#3 SilverAstrid  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 16-January 10

Re: Infinite Loop in c# foreach

Posted 08 February 2012 - 04:06 PM

View PosttlhIn`toq, on 08 February 2012 - 03:47 PM, said:

SilverAstrid What this shows us is that you aren't familiar with breakpoints and how to debug your own code.Learning to debug one's own code is an essential skill. Sadly, one that apparently no college course teaches. Silly if you ask me.

Placing breakpoints and walking through the code line by line allows you to actually WATCH it execute. Visualizing what your code does will let you see why it behaves the way it does.

It would be well worth your time to do the tutorials on FAQ 2. A couple hours learning this skill will save you hundreds of hours of confusion in one project alone.

TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Form1 talk to Form2



FAQ (Frequently Asked Questions - Updated Jan 2012

Spoiler


Quote

I also read somewhere that if your code throws an exception it can get caught? That doesn't sound right to me,


Why doesn't that sound right? You do it in your example:
try
{
     intValue = Convert.ToUInt64(intText);
}
catch
{
     return false;
}



A foreach simply cannot become an infinate loop because collections are not infinite. That have a defined set of values.

Of course if you have methodA, that calls methodB, that calls methodA... now you have a circular reference that will eventually overflow the stack and cause a stackoverflow exception.

So why is you think you have an infinte loop going on here?


I know how to debug. All the debugger is telling me currently is that I'm getting " first chance exception of type 'System.FormatException' occurred in mscorlib.dll". I've stepped through the code and watched it happen, and it's coming from that try block. I say it's infinite looping because my code will get completely stuck in that inner loop (foreach (string statKey in collection.Keys)). It won't exit, go back out to the other loops, and I know there's not enough data I'm working with to cause this to run for minutes like it is (I stop it). I told you the two things I've read online that might cause that issue but I can't seem to find them in my code so I came here for help.


Do you think I might be getting some sort of circular method call here?

And my college does teach debugging =] Neat, huh?

Quote

A foreach simply cannot become an infinate loop because collections are not infinite. That have a defined set of values.


Yes, it can infinite loop, if you are adding to the collection while iterating over it. That got taught to me in college =]
Was This Post Helpful? 0
  • +
  • -

#4 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2271
  • View blog
  • Posts: 9,500
  • Joined: 29-May 08

Re: Infinite Loop in c# foreach

Posted 08 February 2012 - 05:27 PM

Sorry tlhIn`toq but you can have infinite "collections" in .net via the use of the yield

public IEnumerable<Integer> GetRandom()
{
 while (true)
 {
  yield 4;
 }
}



If do a .Last or .Count on that, I suggest that you go away and evolve into more intelligent species.
Was This Post Helpful? 1
  • +
  • -

#5 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5677
  • View blog
  • Posts: 12,209
  • Joined: 02-June 10

Re: Infinite Loop in c# foreach

Posted 08 February 2012 - 05:35 PM

Ok. I'm wrong. It can be done if you look for a way to do it.

But personally, in the real world when you are actually dealing with collections of things...
Was This Post Helpful? 0
  • +
  • -

#6 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2271
  • View blog
  • Posts: 9,500
  • Joined: 29-May 08

Re: Infinite Loop in c# foreach

Posted 08 February 2012 - 06:05 PM

SilverAstrid Could substanciate on your claim that adding to a collection in a foreach can result on an infinite loop?

As when I do it I get an error.

System.InvalidOperationException was unhandled
  Message=Collection was modified; enumeration operation may not execute.
  Source=mscorlib
  StackTrace:
       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
       at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
       at System.Collections.Generic.List`1.Enumerator.MoveNext()
       at ConsoleApplication2.Program.Main(String[] args) in C:\Users\Adam\AppData\Local\Temporary Projects\ConsoleApplication2\Program.cs:line 14
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      var xs = new List<int>();
      xs.Add(1);
      foreach (var x in xs)
      { xs.Add(x+1); }
    }
  }
}



Was This Post Helpful? 0
  • +
  • -

#7 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1012
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: Infinite Loop in c# foreach

Posted 08 February 2012 - 06:34 PM

What's the code for collection.TryGetStat()? You say it has that block, but does it have anything else? If it doesn't, why aren't you using TryParse?
Was This Post Helpful? 0
  • +
  • -

#8 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2271
  • View blog
  • Posts: 9,500
  • Joined: 29-May 08

Re: Infinite Loop in c# foreach

Posted 08 February 2012 - 08:44 PM

Note: You can get an "Infinite" Loop (really a very long one, which will crash when the list count exceeds Integer.Max or it runs out of memory).

Adding to the collection you're looping through.
    static void Main(string[] args)
    {
      var xs = new List<int>();
      xs.Add(1);
      for (var i=0; i < xs.Count; i++)
      { xs.Add(xs[i]+1);}
    }


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1