编译器如何将返回值转换为return 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< T>
中。
You can think of async
as wrapping results (both return values and exceptions) into a Task<T>
.
等待
解开结果(提取返回值或引发异常)。
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.
这篇关于编译器如何将返回值转换为return Task< value>在异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!