Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what context am I running in C#?

Tags:

c#

.net

.net-4.0

I was wondering...

When I have a code like this:

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

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

What about:

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

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

The same question can be asked 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.

like image 602
Royi Namir Avatar asked Jul 07 '12 12:07

Royi Namir


People also ask

What is the context in C#?

A context is an ordered sequence of properties that define an environment for the objects resident inside it.

What is context. net?

What Does Context Mean? In the . NET Framework, context is a set of properties that defines the environment for its residing objects. It specifies the object requirements of an application domain process as an ordered sequence of properties.


2 Answers

It isn't completely impossible, you can use the StackTrace class to get a reference to the caller method and MethodInfo.GetMethodBody() to get the IL of that method.

But you'll never get this reliable, the just-in-time compiler's optimizer will give you a very hard time figuring out exactly where the call is located. Method body inlining will make the method disappear completely. Loop unrolling will make it impossible to get any idea about the loop index. The optimizer uses cpu registers to store local variables and method arguments, making it impossible to get a reliable variable value.

Not to mention the tin foil chewing effort involved in decompiling IL. None of this is anywhere near the simplicity and speed of just passing an argument to the method.

like image 127
Hans Passant Avatar answered Oct 05 '22 06:10

Hans Passant


No (barring code that explicitly forwards this information to the method of course).

The reason for this is that concepts such as these do not get translated to structured information that is preserved in either IL or metadata, which the CLR could then expose to you at runtime. Contrast this with classes which do get encoded in metadata, thus enabling reflection at runtime.

Attempting to preserve this information would result in increased complexity and of course additional overhead for no benefit really since it's easy to implement this in code if you need your program to keep such state (whether it's a good idea to require this state is another issue).

like image 25
Jon Avatar answered Oct 05 '22 08:10

Jon