2013-09-26 45 views
7

因爲我可以定義一個動作作爲檢查行動是異步拉姆達

Action a = async() => { }; 

我可以以某種方式確定(在運行時)的動作是否是異步或不?

+0

這是什麼情況,你不知道它是否? – musefan

+3

@musefan當它是一個輸入框架的DLL –

回答

13

否 - 至少不明智。 async只是一個源代碼註釋,告訴C#編譯器您確實需要一個異步函數/匿名函數。

可以MethodInfo爲代表,並檢查其是否已應用適當的屬性。我個人不會 - 需要知道的是一種設計氣味。特別是考慮,如果你重構大部分代碼出來的lambda表達式的會發生什麼事成另一種方法,則使用:

Action a =() => CallMethodAsync(); 

在這一點上,你有一個異步的λ,但語義會是一樣的。爲什麼你會希望使用委託的代碼具有不同的行爲?

編輯:此代碼似乎工作,但我會強烈反對它

using System; 
using System.Runtime.CompilerServices; 

class Test 
{ 
    static void Main()   
    { 
     Console.WriteLine(IsThisAsync(() => {}));  // False 
     Console.WriteLine(IsThisAsync(async() => {})); // True 
    } 

    static bool IsThisAsync(Action action) 
    { 
     return action.Method.IsDefined(typeof(AsyncStateMachineAttribute), 
             false); 
    } 
} 
+0

我明白了。感謝你的回答! –

+2

我的好奇心越來越好。你爲什麼強烈建議反對它? –

+0

@DavidBožjak:我的好奇心越來越好。你爲什麼要使用這段代碼? – Brian

3

當然,你可以做到這一點。

private static bool IsAsyncAppliedToDelegate(Delegate d) 
{ 
    return d.Method.GetCustomAttribute(typeof(AsyncStateMachineAttribute)) != null; 
}