Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

.net - Is there a simple way to obtain all the local variables in the current stack frame in C# (or CIL)

Following my previous question, in which I wanted to dump all the variables in the stack (from the current and all the previous frame) that can be seen here: Is there a way to examine the stack variables at runtime in C#?

I was suggested to intercept the calls manually or use AOP framework like PostSharp to simplify such a task. I looked at PostSharp and the interception arguments don't include the variables in the current stack frame. I wonder if there is a simple way to automatically get all the local variables in the current stack frame. I suppose I can perform code analysis and generate code that copies all those values into a collection, but maybe there is a built-in mechanism that does it.

Thanks in advance for any suggestions.

EDIT: I should have given more detail of why I want to do this. I want to be able to suspend execution in the middle of a method. If I had the contents of the stack I could resume execution later, or even serialize it and continue it in another machine (assuming it is relatively simple code, so no threads or I/O for example). It is ok to run a code analysis tool that would allow me to automatically generate extra code that saves this state. I think I will probably have to analyze the CIL to do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
   System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();
        System.Diagnostics.StackFrame frame = trace.GetFrame(0);
        MethodBase method = frame.GetMethod();
        MethodBody methodBody = method.GetMethodBody();
        if (methodBody != null)
        {
            foreach (var local in methodBody.LocalVariables)
            {
                Console.WriteLine(local);
            }
        }
        Console.ReadKey();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...