2016-12-05 73 views
2

我想獲取所謂的函數的方法的名稱,這似乎有點問題與Tpl如何僅在使用TPL時從自己的方法獲取堆棧跟蹤?

有沒有什麼好的解決方案?

BTW:我知道CallerMemberName的,但我想不同的解決方案,這樣就不會弄亂我的代碼

這裏是我的測試代碼,以便可以在TPL

class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.WriteLine(F1().Result); 
     Console.ReadKey(); 
    } 

    static async Task<string> F1() 
    { 
     return await F2(); 
    } 

    static Task<string> F2() 
    { 
     var callingMethods = new StackTrace().GetFrames().Select(v => v.GetMethod().Name); 
     var result = string.Join(Environment.NewLine, callingMethods); 
     return Task.FromResult(result); 
    } 
} 

下一個版本的破解這是輸出

F2

MoveNext的

開始

F1

主要

...

+0

你有沒有考慮** **爲什麼它是一個有點與TPL的問題? – Maarten

+0

因爲他們之間放置了另一層 – Yacov

回答

4

你可以通過檢查裝配過濾掉不屬於自己所有的組件,例如是不是在GAC :

var callingMethods = new StackTrace().GetFrames() 
         .Select(v => v.GetMethod()) 
         .Where(m => !m.DeclaringType.Assembly.GlobalAssemblyCache 
            && !m.DeclaringType.CustomAttributes.Any(ca => ca.AttributeType == typeof(CompilerGeneratedAttribute)) 
           ) 
         .Select(m => m.Name); 

輸出:

F2

F1

主要

相關問題