current method name

R

rodchar

hey all,

is there a way to retrieve the name of the method that the current thread is
executing in?

thanks,
rodchar
 
A

Alberto Poblacion

rodchar said:
is there a way to retrieve the name of the method that the current thread
is
executing in?

You can use System.Diagnostics.StackTrace to get the top stack frame. Be
aware that this is a slow operation.
 
P

Pavel Minaev

    You can use System.Diagnostics.StackTrace to get the top stack frame. Be
aware that this is a slow operation.

Furthermore, be aware that it will not always give the "correct"
answer, because the JIT compiler can and does inline methods, in which
case there might not be a stack frame for yours (so you get the one
which called you instead).

In practice, this is almost always a useless operation, anyway. At any
given place in the code, you already know the answer at compile-time.
Knowing the name of the _calling_ method can be useful, but see above
for why it's still not a good idea. Whatever you're trying to do, it
is most likely better done in a different way.
 
A

Arne Vajhøj

rodchar said:
is there a way to retrieve the name of the method that the current thread is
executing in?

I know of 3 options:

1)

MethodBase method = (new StackTrace(true)).GetFrame(0).GetMethod();
string methodname = method.DeclaringType.FullName + "." + method.Name;

2)

MethodBase method = MethodInfo.GetCurrentMethod();
string methodname = method.DeclaringType.FullName + "." + method.Name;

3)

MethodTracker.GetCurrentMethod()

where MethodTracker is the code below and weaved in via
AspectDNG.

Arne

==========================================

using System;
using System.Collections.Generic;
using System.Threading;

using DotNetGuru.AspectDNG.Joinpoints;

public class MethodTracker
{
private static Dictionary<int, Stack<string>> methods = new
Dictionary<int, Stack<string>>();
public static string GetCurrentMethod()
{
return methods[Thread.CurrentThread.ManagedThreadId].Peek();
}
[AroundCall("* YourNameSpace.YourClass::*(*)")]
public static object SaveMethod(JoinPoint jp)
{
if(jp is MethodJoinPoint)
{
if(!methods.ContainsKey(Thread.CurrentThread.ManagedThreadId))
{
methods.Add(Thread.CurrentThread.ManagedThreadId, new
Stack<string>());
}
MethodJoinPoint mjp = (MethodJoinPoint)jp;

methods[Thread.CurrentThread.ManagedThreadId].Push(mjp.TargetOperation.DeclaringType.FullName
+ "." + mjp.TargetOperation.Name);
}
object res = jp.Proceed();
if(jp is MethodJoinPoint)
{
methods[Thread.CurrentThread.ManagedThreadId].Pop();
}
return res;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top