Explicitly use a Func for asynchronous lambda function when Action overload is available

前端 未结 4 1089
死守一世寂寞
死守一世寂寞 2020-12-13 17:38

Reading over this blog post on some of the gotchas of C#5\'s async/await. It mentions in Gotcha #4 something that is quite profound and that I hadn\'t thought of before.

4条回答
  •  轮回少年
    2020-12-13 18:14

    Because Task.Run has signatures of both Task.Run(Func) and Task.Run(Action), what type is the async anonymous function compiled to? An async void or a Func? My gut feeling says it will compile down to an async void purely because its a non-generic type however the C# Compiler might be smart and give Func types preference.

    The general rule, even without async, is that a delegate with a return type is a better match than a delegate without a return type. Another example of this is:

    static void Foo(Action a) { }
    static void Foo(Func f) { }
    static void Bar()
    {
      Foo(() => { throw new Exception(); });
    }
    

    This is unambiguous and calls the second overload of Foo.

    Also, is there a way to explicitly declare which overload I wish to use?

    A nice way to make this clear is to specify the parameter name. The parameter names for the Action and Func overloads are different.

    Task.Run(action: async () => {
      await Task.Delay(1000);
    });
    Task.Run(function: async () => {
      await Task.Delay(1000);
    });
    

提交回复
热议问题