在仅等待return语句时将方法标记为异步是否有用? [英] Is it useful to mark a method async when it only awaits at the return statement?
问题描述
以下方法的最后一行仅在方法返回之前使用'await',因此这并不意味着该方法基本上是同步的,应仅在没有async修饰符和后缀异步?
Only the last line of the method below is using 'await', just before the method returns, so doesn't this mean that method is basically synchronous and should just be called "Get()" without the async modifier and the suffix Async?
public virtual async Task<TEntity> GetAsync(Guid id)
{
// some more code here
return await _dbSet.FindAsync(id);
}
推荐答案
这并不意味着该方法基本上是同步的
doesn't this mean that method is basically synchronous
不.它是异步的.您可能正在考虑顺序(从一件事到另一件事),而不是 synchronous (阻止当前线程). await
将(顺序)暂停该方法,但不会(异步)阻止该线程.有关更多信息,请参见我的 async
简介.
No. It's asynchronous. You're probably thinking of sequential (progressing from one thing to the next), not synchronous (blocking the current thread). An await
will pause the method (sequentially) but not block the thread (asynchronously). For more information, see my async
intro.
没有异步修饰符
without the async modifier
尽管您可以忽略async
/await
关键字,但我建议您不要这样做.这是因为// some more code here
可能会引发异常.我在消除async
和await
.
While you could elide the async
/await
keywords, I would recommend that you do not. This is because // some more code here
may throw an exception. I cover this and other considerations in my blog post on eliding async
and await
.
和后缀Async?
and the suffix Async?
否,该后缀适用于任何返回等待状态的方法(例如Task
).因此,即使您忽略了async
和await
,它仍然会返回要等待 的任务,因此它仍应具有Async
后缀.
No, that suffix is appropriate for any method that returns an awaitable (e.g., Task
). So, even if you elide the async
and await
, it's still returning a task that should be awaited, so it should still have the Async
suffix.
您可以这样想:Async
后缀是API接口的一部分. async
关键字是实现的详细信息.他们经常在一起,但并非总是如此.
You can think of it this way: the Async
suffix is part of the API interface. The async
keyword is an implementation detail. They often go together, but not always.
这篇关于在仅等待return语句时将方法标记为异步是否有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!