views:

600

answers:

4

I have a basic foreach loop that calls a static method which makes a connection to a database and inserts some data. For some reason it will only iterate through the first item in the collection when I run the application without debugging. If I debug the application and set a break point on the foreach loop, it will iterate through all of the items in the collection.

If I set a break point and step over the foreach loop, it will demonstarte the same behavior as if I was running the application without debugging.

Does anyone know what would cause this type of behavior?

Here is a simplified version of the source code:

List<MyObject> objectlist = new List<MyObject>();

//some code to populate list

foreach(MyObject myobject in objectlist)
{
    string a = "a";
    string b = "b";

    MyLibrary.UpdateDatabase(a, b);
}

(I am using Visual Studio 2008 SP1)

Update

The process does not throw any exceptions with or without debugging the application.

+5  A: 

My guess would be that your code might be behaving differently when you give it more time by stepping through each line. (Presumably because of the database)

Make sure that the method isn't throwing any exceptions (put a catch block that calls Console.WriteLine or MessageBox.Show and see if anything happens).

Look in the database logs and see if there's anything interesting there.

Also, please post the full source of the method.

SLaks
Turning debug break on Exceptions is great for spotting these kind of things- http://msdn.microsoft.com/en-us/library/d14azbfh.aspx
RichardOD
Yes, but he says it mainly happens when not running under the debugger, so that's not enough.
SLaks
I was referring to the "Make sure that the method isn't throwing any exceptions" as a comment- I've not posted an answer...
RichardOD
What?
SLaks
+2  A: 

Normally when there is a difference between code running normally and code running in debug, it is related to the security context.

Code running in a process will run in the security context of that process. Code running in debug mode will run in the security context of the user doing the debugging.

The call to the database probably fails when the code is run normally, due to lack of rights. It would then appear that the loop only runs once.

Shiraz Bhaiji
+1  A: 

It was not iterating through the foreach loop when I was not debugging the application because the myobject object was not used in the UpdateDatabase method call.

My source code should look like this:

List<MyObject> objectlist = new List<MyObject>();

//some code to populate list

foreach(MyObject myobject in objectlist)
{
    MyLibrary.UpdateDatabase(myobject.a, myobject.b);
}
Michael Kniskern
Please update your original question when you have clarification (that's how SO works ;))
peterchen
Wouldn't this answer been enough clarification?
Michael Kniskern
A: 

For me it sounds like an exception. Just to be sure, did you checked everything in Debug - Exceptions to On?

Oliver