Under what context am I running in C#?

Deadly 提交于 2019-12-08 17:12:29

问题


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.


回答1:


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.




回答2:


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).




回答3:


I don't believe that .NET supports the features you describe directly, although you might be able to get at that information by using StackFrame to grab the current call stack, and using reflection to analyse method bodies etc. but I'm not sure how precise you could ever be.

.NET does have contexts for synchronization, but not at the level you are asking about. Check out System.ContextBoundObject for example.



来源:https://stackoverflow.com/questions/11374916/under-what-context-am-i-running-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!