如何解决对C#异步方法结果执行操作
我正在将一些同步代码转换为C#(.NET 4.5)中的异步代码。我有一个问题,需要使用远程查询检索到的模型数量作为输入来进行操作。
所需行为的示例:
public async Task<List<Model>> GetEntityModelsAsync()
{
return // some models from a database async
}
public async Task<int> DoSomeWorkWithModelCount()
{
Task<IEnumerable<Model>> models = GetEntityModelsAsync();
// some other code to execute before awaiting
int count = await models.Count();
// do more work and return result
}
以上代码将不会编译为错误“ Task
我认为这是因为变量的类型是'Task
我尝试以这种方式获得结果:
int count = await models.Result.Count(); // error: 'int' does not contain a definition for 'GetAwaiter'
await recentApplications.GetAwaiter().GetResult(); // error: 'int' does not contain a definition for 'GetAwaiter'
我被迫首先等待结果进入另一个这样的变量:
IEnumerable<Model> modelsResult = await models;
int count = modelsResult.Count();
还是有一种更简化的方法来对等待的任务的结果执行类型操作?
解决方法
如果要在一行中执行此操作,则该操作:
int count = (await models).Count();
,
使用
int count = await models.CountAsync();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。