2

You can only await an async method. However that async method itself needs to have an await statement inside it itself. Doesn't this lead to an infinite regression?

David Klempfner
  • 8,700
  • 20
  • 73
  • 153

2 Answers2

3

No for a couple of reasons

  • An async method is not required to have an await, it's just recomended
  • An await expression can target items like Task<T>
  • An async method can be called from a non-async method

Here is a simple example that has terminates

async Task<int> Add(Task<int> task, int value) { 
  var t = await task;
  return t + value;
}

Task<int> t;
Task<int> t2 = Add(t, 42);
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
2

You can only await an async method.

That's not true. You can await anything that follows the "awaitable pattern" (something with a GetAwaiter() method, the return type of which has appropriate IsCompleted, GetResult(), and OnCompleted() members.

Note that even when you're awaiting the result of calling an async method, it really is the result that you're awaiting... and it doesn't matter that the result happened to be from an async method. As far as the compiler's concerned, you're just awaiting a Task or a Task<T>, which was the result of a method call. The async part only matters within the implementation of the method.

You can await other things as well though - for example, Task.Yield returns a YieldAwaitable which isn't a task, but which implements the awaitable pattern. You can implement the awaitable pattern yourself (and cause all kinds of fun mayhem by doing so, should you wish to).

However that async method itself needs to have an await statement inside it itself.

Again, not true - although the compiler will warn you if you don't have an await expression within an async method, as that's almost always a sign that you're doing something wrong.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194