对C#异步方法结果执行操作

时间:2020-08-17 16:43:11

标签: c# .net async-await

我正在将一些同步代码转换为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 ”,其中不包含“ Count”的定义...

我认为这是因为变量的类型是'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();

还是有一种更简化的方法来对等待的任务的结果执行类型操作?

2 个答案:

答案 0 :(得分:3)

如果要在一行中执行此操作,则该操作:

int count = (await models).Count();

答案 1 :(得分:1)

使用

int count = await models.CountAsync();
相关问题