假设我有这样的方法:
private async Task SomeMethod()
{
await DoSomethingAsync();
await DoSomethingElseAsync();
return;
}
鉴于DoSomethingElseAsync
返回 Task
看起来你应该能够做到这一点:
private async Task SomeMethod()
{
await DoSomethingAsync();
return DoSomethingElseAsync();
}
但是编译器对此有提示:
Since '
SomeMethod
' is an async method that returns 'Task
', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>
'?
这是为什么?
最佳答案
这很像yield return
和 return
作品。对于迭代器,您有这些方法之一
public IEnumerable<int> SomeIterator()
{
for(int I = 0; I < 10; I++) yield return I;
}
public IEnumerable<int> SomeIterator()
{
return Enumerable.Range(0, 10); // return result of another iterator.
}
但你不能两者兼得。它不起作用,因为编译器将迭代器转换为类以处理 yield
的惰性迭代,或者它就像其他返回其他内容的普通方法一样。
public IEnumerable<int> SomeIterator() // not valid
{
for(int I = 0; I < 10; I++) yield return I;
return Enumerable.Range(0, 10);
}
关于return
的故事是一样的和 async/await
.对于返回类型为 Task
的方法你要么返回Task
或使用 async/await
.
Task<T>
如果你使用 await 你必须返回 T
但你不能返回 Task<T>
因为方法被编译成状态机,那么方法必须返回T
. (对于 Task
方法无效)
如果你不使用 async/await
方法将与其他普通方法完全一样。
关于c# - 在异步函数中,为什么我必须等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46662428/