Does the VS2008 debugger hold on to out of scope objects?
Given this snippet of code:
// Get first key //
int? keyEDISecurity = this.WorkQueue.GetNextWorkItem();
// Done? //
while (keyEDISecurity != nu开发者_开发知识库ll)
{
try
{
...
// Write changes //
List<ISNLEditableObject> changedRows = this.WorkQueue.GetChangedRows((int)keyEDISecurity);
this.Writer.Write(changedRows, WriteFlags.Transactional);
...
}
catch (Exception ex)
{
// Exception handling/logging code
}
finally
{
// Remove all data for the KeyEDISecurity from work queue cache //
this.WorkQueue.RemoveData((int)keyEDISecurity);
}
// Get next work item //
keyEDISecurity = this.WorkQueue.GetNextWorkItem();
}
Before the line with the declaration List changedRows, changedRows is null, as it should be. It then goes out of scope, as you get the next work item. You then come back in, and before that same line, if you access changedRows, it should be again null, as it hasn't be declared.
If you break and edit, then, as you expect, you can't access changedRows, because it's gone out of scope, and not been declared yet. If you evaluate it (either by mouseover or using the immediate window), you have access to the changedRows from the previous iteration of the loop. WTH?
Anyone seen this? It doesn't affect the program as it seems to act correctly in code, but the debugger issue caused a waste of time since it wasn't behaving as expected. I was wondering if this was expected behaviour or not, so I could know in the future and not waste time with it.
This is implementation specific optimization.
When function is executed, all its variables are usually created on the stack at once. Even though the language does not permit to access them yet, they are there. This is why changedRows
is null
before it has even been declared.
When the variable goes out of scope, the language does not permit to use it again, but it's still there on the stack. Its value does not need to be changed to null
, because it won't be used anywhere. It will be waste of processor time. This is why value of changedRows
is preserved, even though, according to language rules, it must be destroyed (when it goes out of scope) and created again (when it is declared).
Debugger does not respect all language rules. In fact, it may even be confused by some constructs. When you try to get value of a variable, the debugger does not check if it is in scope etc.
精彩评论