2017-02-09 56 views
0

我想通過使用反射等得到這種方法的名稱...我使用了很多東西,但我累了,請幫助我。 如果該功能是同步,那麼它下面的代碼將正常工作。請通過下面的代碼,這將清除你的我的問題。我們如何才能得到異步方法名稱在c#

// this will work fine 
public void Test() 
{ 
// This GetCurrentMethod() will you the name of current method 
string CurrentMethodName = GetCurrentMethod(); 
// output will be CurrentMethodName = Test 
} 


// this will not work 
     public async Task<int> GETNumber(long ID) 
     { 
// This GetCurrentMethod() will you the name of current method if the method is sync or not async 
string CurrentMethodName = GetCurrentMethod(); 
      return await Task.Run(() => { return 20; }); 
     } 

此方法爲我提供了非異步方法的名稱。但我如何得到以上方法名稱

>  [MethodImpl(MethodImplOptions.NoInlining)] 
>   public static string GetCurrentMethod() 
>   { 
>     var stackTrace = new StackTrace(); 
>     StackFrame stackFrame = stackTrace.GetFrame(1); 
>     return stackFrame.GetMethod().Name; 
>   } 

但是,此方法只適用於不是異步方法。那麼如何在c#中獲取當前的異步方法名稱?

+0

這裏的問題是,在你的特定情況下,使用'Task.Run'的「堆棧」不是一個自然堆棧,因此線程池線程已經啓動運行你的匿名方法,因此,堆棧不包含特定於「GETNumber」方法的任何內容。 *但是,在這種特殊情況下,匿名方法的生成名稱包含名稱,該方法的名稱就像''。 b__1_0'。 –

+0

現在,問題是,你到底需要什麼名字? –

+0

檢查:[從異步函數獲取當前方法名稱](http://stackoverflow.com/q/20158902/1351076) – krlzlx

回答

1

你想要的不是真的可能。編譯器爲async方法創建狀態機,類似的東西

public class GetNumberStateMachine : IAsyncStateMachine 
{ 
    // .... 
    void IAsyncStateMachine.MoveNext() 
    { 
     // here your actual code happens in steps between the 
     // await calls 
    } 
} 

而且你的方法轉換成類似的東西:

public async Task<int> GetNumber() 
{ 
    GetNumberStateMachin stateMachine = new GetNumberStatemachine(); 
    stateMachine.\u003C\u003Et__builder = AsyncTaskMethodBuilder<int>.Create(); 
    stateMachine.\u003C\u003E1__state = -1; 
    stateMachine.\u003C\u003Et__builder.Start<GetNumberStatemachine>(ref stateMachine); 
    return stateMachine.\u003C\u003Et__builder.Task; 
} 

那麼什麼叫你GetCurrentMethod()在運行時不再是你GetNumber()


但是你可以通過CallerMemberNameAttribute獲得主叫方法的名稱:

public static string GetCurrentMethod([CallingMemberName] string method = "") 
{ 
    return method; 
} 

public async Task<int> GetNumber(long ID) 
{ 
    int result = await Task.Run(() => { return 20; }); 
    Console.WriteLine(GetCurrentMethod()); // prints GetNumber 
    return result; 
} 

這甚至與async方法工作(我不知道,但我猜的說法被替換在編譯時間)。

+0

備註 - 對於產生結果的迭代器方法也是如此。雖然還有可能得到包含狀態機的方法的名字嗎? –

相關問題