Why does this async / await code generate "... not all code paths return a value"?

I hope this is not a repetition, but there are 5000 more questions in which "not all code paths return a value"!

Simply put, why this non-standard implementation method compiles just fine:

public static async Task TimeoutAfter(this Task task, int millisecondsTimeout) { if (task == await Task.WhenAny(task, Task.Delay(millisecondsTimeout))) await task; else throw new TimeoutException(); } 

while this attempt to make a generic method generates a warning Return state missing / ... not all code paths return a value :

  public static async Task<T> TimeoutAfter<T>(this Task<T> task, int millisecondsTimeout) { if (task == await Task.WhenAny(task, Task.Delay(millisecondsTimeout))) await task; else throw new TimeoutException(); } 
+6
source share
2 answers

The unoriginal type of Task somewhat equivalent to the expected void method. Just like the void method, you cannot return anything from a method that has a return type of Task , so the first example compiles. The second example, however, expects the return value of the generic type, and you do not provide it in the path where you expect another call.

A quote from the MSDN link in the async key, in particular about return types.

You use Task if the value of the significant value is not returned when the method is completed. That is, the method call returns the task, but when the Task is completed, any pending expression that is waiting for the task is evaluated as invalid.

+8
source

In the second example you gave, you did not return anything. (See Chris Hannon, answer to the question why).

 public static async Task<T> TimeoutAfter<T>(this Task<T> task, int millisecondsTimeout) { if (task == await Task.WhenAny(task, Task.Delay(millisecondsTimeout))) return await task; // return the Task of T else throw new TimeoutException(); } 

In addition to what @ChrisHannon said, from waiting for documentation .

... if await is applied to the result of a method call that returns a Task<TResult> , then the type of the pending expression is TResult . If await is applied to the result of calling a method that returns a Task , then the type of the waiting expression is void ....

+7
source

Source: https://habr.com/ru/post/923701/


All Articles