[英]Why does this async / await code generate “…not all code paths return a value”?
希望这不是重复,但这里有5000多个问题,“并非所有代码路径都返回值”!
很简单,为什么这个非泛型实现的方法编译得很好:
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();
}
虽然这种使方法通用的尝试会生成一个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();
}
在第二个例子中,你给了你没有返回任何东西。 (参见Chris Hannon的回答为什么)。
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();
}
除了@ChrisHannon所说的,还有等待文档 。
...如果将
await
应用于返回Task<TResult>
的方法调用的结果,则await表达式的类型为TResult
。 如果将await
应用于返回Task
的方法调用的结果,则await表达式的类型为void
。 ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.