【问题标题】:If i add async keyword to a method which which should return a Task it wrap the return value in Task?如果我将 async 关键字添加到应该返回任务的方法中,它会将返回值包装在任务中?
【发布时间】:2021-01-07 02:15:53
【问题描述】:

如果在没有异步的情况下编写此函数并等待作为此示例,我会收到错误,我应该返回任务而不是用户对象

public Task<User> Register(User user, string password)
    {
        byte[] passwordhash,passwordsalt;

        CreatePassword(password,out passwordhash,out passwordsalt);

        return user;
    }

但是如果用 async 和 await 编写这个函数作为这个例子它可以正常工作,所以我想知道是否将 async 关键字添加到任何方法它应该自动将返回值包装到 Task

public async Task<User> Register(User user, string password)
    {
        byte[] passwordhash,passwordsalt;
        CreatePassword(password,out passwordhash,out passwordsalt);

        await _Context.Users.AddAsync(user);
        await _Context.SaveChangesAsync();

        return user;
    }

【问题讨论】:

标签: c# .net asynchronous async-await task


【解决方案1】:

如果将 async 关键字添加到任何方法,它应该自动将返回值包装到任务中

是的。一种思考方式是async 将返回值(或异常)包装到Task(或类似任务)中。并且await“解包”返回值(或异常)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 2017-08-25
    • 2020-02-29
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多