c# - 返回任务而不是等待内部方法调用

标签 c# asynchronous async-await task

<分区>

我看到一些同事代码,他选择不等待数据库调用而只返回任务。例如

public Task<UpdateResult> AddActivityAsync(ClaimsPrincipal principal, Activity activity)
{
    return _userManager.SaveToDatabaseAsync(principal, activity);
}

因为 _userManager.SaveToDatabaseAsync 是异步的,我会用这种方式实现

public async Task<UpdateResult> AddActivityAsync(ClaimsPrincipal principal, 
                                                                      Activity activity)
{
    return await _userManager.SaveToDatabaseAsync(principal, activity);
}

这个方法的调用方法总是等待它:

await _profile.AddActivityAsync(..., ...)

不使内部方法异步并只返回任务,让调用者等待它有什么好处吗?我以为我们必须一直写 Async ...

最佳答案

视情况而定

必须等待,例如,如果要等待的代码绑定(bind)到using 上下文中的对象(或手动处理):

using (SomeDisposableType obj = ...)
{
    await obj.SomeOperationAsync();
}

如果您没有等待就返回了任务,那么该方法可能会提示该对象在完成其工作之前已被释放。 (不是所有的一次性对象都会抛出 ObjectDisposedException ,如果你试图在它们被处理后对它们执行某些操作,但通常这样假设是个好主意)。考虑相反的情况:

using (SomeDisposableType obj = ...)
{
    // This returns the Task that represents the async operation,
    // and because it returns, the control goes out of the using
    // scope, and therefore obj gets disposed.
    return obj.SomeOperationAsync();
}

所以有些情况下等待是必要的。如果不是这种情况,我真的想不出您不能返回 Task 本身的原因。

关于c# - 返回任务而不是等待内部方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42716445/

相关文章:

asynchronous - Tokio react 器是否轮询每个组合器之间所有可能的 poll() 函数?

node.js - asyncjs -eachSeries() 不会迭代数组中的所有项目

async-await - 如何使用 Rust 中新的异步等待语法通过 H2 执行 HTTP2 请求?

c# - 我的 Controller 方法是异步执行的吗?

c# - HttpClient 忽略 AllowAutoRedirect 指令

c# - 如何从 MVC 中的 DateTime 变量中删除时间部分

c# - 从存储为字符串的 html 中输出前两段

c# - 反序列化 JSON 项目

c# - 如何从 C# 中的异步任务 <bool> 函数获取 bool 结果 - 错误 : Cannot implicitly convert type `void' to `bool'

javascript - 为什么 async/await 变量返回未定义?