编译器如何将返回值转换为返回值 Task<value>在异步方法中? [英] How does compiler converts return value into return Task<value> in async methods?
问题描述
我设计了以下方法来创建记录.
I've designed the following method to create records.
public Task<Guid> NotAwaited()
{
Account account = new Account();
Context.Accounts.Add(account);
Context.SaveChangesAsync();
return new Task<Guid>(() => account.Id);
}
然后,我意识到在返回 guid 的那一刻,存在保存未完成的风险.所以我添加了await
,它要求我用async
来装饰方法签名.在那之后,我收到了一个错误,要求对返回的内容使用更简单的语法,就像这样.
Then, I realized that there's risk of the saving not being finished at the moment of returning the guid. So I've added await
, which required me to decorate the method signature with async
. Upon that, I got an error demanding a simpler syntax of what's being returned, like this.
public async Task<Guid> Awaited()
{
Account account = new Account();
Context.Accounts.Add(account);
await Context.SaveChangesAsync();
return account.Id;
}
我知道 account.Id
部分会以某种方式转换为任务.我只是不确定如何.感觉就像是黑魔法(我理解它不是).
I understand that the account.Id
part gets converted to a task somehow. I'm just uncertain how. It feel like if it's black magic (which I understand it isn't).
是否存在隐式转换?还是我执行的异步调用仍然不正确?
Is there an implicit conversion? Or am I still performing the asynchronous call improperly?
推荐答案
您可以将 async
视为将结果(包括返回值和异常)包装到一个 Task
中代码>.
You can think of async
as wrapping results (both return values and exceptions) into a Task<T>
.
同样,await
解包结果(提取返回值或引发异常).
Likewise, await
unwraps the results (extracting the return value or raising an exception).
我有一个 async
介绍 更详细,我推荐 async代码>最佳实践
作为后续.附带说明一下,你永远不应该使用 Task
构造函数.
I have an async
intro that goes into more detail, and I recommend async
best practices as followup to that. On a side note, you should never use the Task
constructor.
这篇关于编译器如何将返回值转换为返回值 Task<value>在异步方法中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!