There is a code like this:

class A { void Foo() { } async void FooAsync() => await Task.Run(Foo); } 

Writes an error: "void A.foo ()" has an invalid return type. Kill I do not understand what the matter is ... Here is the Action parameter for Task.Run. Where does the error come from ???

  • one
    @Monk Task.Run and returns Task like. - PECHAPTER
  • one
    casting to Action should help Task.Run((Action)Foo) - Grundy
  • @Grundy for sure! Thanks helped. It was weird that it didn’t recognize it only ... - PECHAIRTER

1 answer 1

The C # compiler does not know how to correctly select the type of delegate in the case of an implicit type conversion to the delegate and method overload with different delegate parameters.

Specifically, in this case, the compiler mistakenly chooses an overload that accepts Func<Task> or Func<T> .

To circumvent this behavior, you can use

  • type explicit cast: await Task.Run((Action)Foo)
  • explicit delegate creation: await Task.Run(new Action(Foo))
  • or lambda expression: await Task.Run(() => Foo())

PS It makes no sense to make methods consisting of a single await operator. It would be possible to remove the words async and await - nothing would have changed.

  • The method will be executed asynchronously. How does it make no sense then? That's the point. - PECHAPTER
  • one
    @DarkByte asynchrony is achieved by calling Task.Run , not by the async . The async does nothing by itself, it only allows the use of await . - Pavel Mayorov
  • I understand that. But I have a call to Task.Run in general, then ... Or are you willing to bet that this function is not executed asynchronously? This is just an asynchronous wrapper of one function over another. Such things are even in .NET. - PECHAPTER
  • @DarkByte asynchronous is called any function that continues to work after it returns, regardless of the presence or absence of the async . - Pavel Mayorov
  • here you are wrong. Without the async keyword, there can be no asynchronous function. - PECHAPTER