I've got sort of a unique situation. I've been working on an open source library for sending email. In this library, I need a reliable way to get the calling method. I've done this with a StackTrace
by analyzing the StackFrame
objects inside it. This works without issue in a debug-mode project where optimizations are turned off.
The problem occurs when I switch to release mode where optimizations are turned on. The stack trace looks like this:
> FindActionName at offset 66 in file:line:column <filename unknown>:0:0
> Email at offset 296 in file:line:column <filename unknown>:0:0
> CallingEmailFromRealControllerShouldFindMailersActionName at offset 184
in file:line:column <filename unknown>:0:0
> _InvokeMethodFast at offset 0 in file:line:column <filename unknown>:0:0
> InvokeMethodFast at offset 152 in file:line:column <filename unknown>:0:0
...
This is taken from a failing unit test. In line 3 of this trace, I should see a method called TestEmail
which is defined elsewhere, but I believe the JITter is inlining it. I've read that you can prevent inlining by making a method virtual, but this doesn't work. Does anyone know of a reliable method for preventing method inlining so your method will show up in a stack trace?
You could use MethodImplAttribute
and specify MethodImplOptions.NoInlining
.
[MethodImpl(MethodImplOptions.NoInlining)]
void YourMethod()
{
// do something
}
Note that this still doesn't guarantee that you can get at the actual calling method as seen in the source code. Your method won't be inlined, but your method's caller could be inlined into its own caller, etc etc.