In what context do I work in C #?

It was interesting to me...

When I have a code like this:

lock (obj) { MyCode.MyAgent(); } 

Can MyAgent contain code that recognizes that it works under a lock block?

What about:

 for (int i=0;i<5;i++) { MyCode.MyAgent(); } 

Can MyAgent contain code that recognizes that it works under a loop block?

You can ask the same question for using blocks, unsafe code, etc ... - well, you get the idea ...

Is this possible in C #?

This is just a theoretical question, I'm not trying to achieve anything ... just knowledge.

+8
source share
3 answers

This is not entirely impossible, you can use the StackTrace class to get a reference to the caller's method and MethodInfo.GetMethodBody () to get the IL of this method.

But you will never get this reliable, the compiler optimizer just in time will give you a very difficult time to figure out exactly where the call is located. Bringing the method into the body will make the method completely disappear. A popup loop scan will make it impossible to know the loop index. The optimizer uses processor registers to store local variables and method arguments, which makes it impossible to obtain a reliable variable value.

Not to mention the increased chewing rigidity of the foil associated with decompilation of IL. None of this comes close to simplicity and speed, just passing the argument to the method.

+8
source share

No (prohibition code that explicitly passes this information to the final method).

The reason for this is that concepts such as these do not translate into structured information that is stored in IL or metadata that the CLR can then provide to you at run time. Contrast this with classes that receive encoding in metadata, which allows reflection at runtime.

An attempt to save this information would lead to increased complexity and, of course, additional overhead without any benefit, since it is easy to implement in code if you need your program to save such a state (is it important to require this state to be another question )

+3
source share

I do not believe that .NET supports functions that you directly describe, although you can get this information by using a StackFrame to grab the current call stack and use reflection to parse methods, etc. m not sure how accurate you have ever been.

.NET has contexts for synchronization, but not at the level you are asking about. For example, System.ContextBoundObject .

0
source share

All Articles