Error settings breakpoints but only on some lines

2019-07-22 02:04发布

问题:

This line is causing the "key not found" in the PostEntityImages collection.

Entity pimage = _context.PostEntityImages["postcreate"];

When I put a break point on that line and put it in the watch window it works fine and that key is present.

UPDATE:

protected override void ExecutePlugin()
{

try
{
    Entity pimage = null;
    if (_context.PostEntityImages.ContainsKey("postcreate"))
        pimage = _context.PostEntityImages["postcreate"];
}
catch (Exception)
{
    // Never hits this line
    throw;
}
} // When stepping in/over the line assigning pimage, execution will jump to this point, then be caught in the catch block of this methods caller.

UPDATE #2:

While in debug mode, some breakpoints set fine. Other give the error "The following breakpoint cannot be set:"

回答1:

The breakpoint and single-step behavior you're describing is usually caused by attempting to debug your project in a "Release" build configuration. In both cases, you are most likely running into cases where the compiler has optimized lines of code away because they are irrelevant.

For example, if you have the following code:

try
{
  throw new ArgumentNullException("foo");
}
catch
{
  var x = 0;
  throw;
}

The catch block above is useless, and the compiler's flow analysis is smart enough to determine that it can be safely optimized away. If you were to step through the code when running such an optimized build, it would just skip right over your exception handler and jump to the caller's exception handlers. It would also produce strange errors setting breakpoints, especially if you tried to set them on an optimized-away line while your program was already being debugged.

In a debug, non-optimized build, the compiler will keep statements that would otherwise be meaningless (such as, assigning values to a variable that is never used again) specifically because they are useful debugging tools.

Make sure that whatever build configuration you are using does not have the "Optimize Code" checkbox set in the project's "Build" properties. Note that the name of the configuration is meaningless to VS -- if you name your project's build configuration "Debug" but turn on optimization, you get a non-debuggable build.