4

Is there a way to dump the contents of the stack at runtime?

I am interested in both the parent functions information (name, parameters, line) which I know I can get with the StackTrace and StackFrame classes. However, I would also like to get the variables in the stack (local variables declared in the method that called the one is currently executing). Since the Visual Studio debugger can do this, I think there may be a way to also do it at runtime within the code. Is there such a way?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
cloudraven
  • 2,484
  • 1
  • 24
  • 49
  • 1
    According to [this post](http://stackoverflow.com/questions/75076/obtain-parameter-values-from-stackframe-in-net) it looks like you cannot do it using StackTrace and StackFrame classes. – Bala R Feb 26 '11 at 23:33
  • Thanks! That is a very similar question. I wonder if there is a simpler way to do this than to use interceptions. – cloudraven Feb 26 '11 at 23:37
  • 2
    Only a debugger can do this and it only does a credible job if the code isn't optimized. This always dies a quick death when you find out that a program cannot debug itself. – Hans Passant Feb 27 '11 at 00:08

1 Answers1

1

I suppose there are two ways of achieving this.

Your first option is to use an AOP framework to inject instrumentation code as a post-compilation step. This can be finely targeted and lets you do pretty much whatever you want, but works best when you can isolate the desired additional behaviors from the rest of the code. PostSharp is the leading contender in this area, but I'm sure there are others.

Your second option is to hook into the profiler API, which is what TypeMock Isolator and Microsoft's own Moles do. It basically gives you the means to intercept everything, but is quite program invasive and surely not a trivial task to implement. In fact, I'd not recommend this approach to anyone except to mention it for completeness.

Morten Mertner
  • 9,414
  • 4
  • 39
  • 56
  • Thanks. PostSharp seems to be quite powerful, and saves me from doing the interception by hand. Perhaps then my question should be. How can I capture the whole state of the current stack frame. It probably makes more sense to post it as a separate question though – cloudraven Feb 27 '11 at 20:46