AsyncPageable<T> 异步获取第一个结果

Dei*_*kis 9 c# async-await

我已经AsyncPageable<T>并且只想获得列表中的第一个结果。

MS 文档建议使用await foreach

// call a service method, which returns AsyncPageable<T>
AsyncPageable<SecretProperties> allSecretProperties = client.GetPropertiesOfSecretsAsync();

await foreach (SecretProperties secretProperties in allSecretProperties)
{
    Console.WriteLine(secretProperties.Name);
}
Run Code Online (Sandbox Code Playgroud)

有没有什么有效的方法可以只得到第一个结果?就像是FirstOrDefaultAsync()

目前我正在使用这段代码来获得第一个结果。

var enumerator = response.Value.GetResultsAsync().GetAsyncEnumerator();
await enumerator.MoveNextAsync();
var result = enumerator.Current;
Run Code Online (Sandbox Code Playgroud)

ryt*_*isk 12

由于AsyncPageable<T>实现了IAsyncEnumerable<T>,您可以安装System.Linq.Async nuget 并使用它提供的方法:

var result = await allSecretProperties.FirstOrDefaultAsync();
Run Code Online (Sandbox Code Playgroud)

  • @DeivydasVoroneckis 你安装了 NuGet 吗? (3认同)
  • 请注意:将“System.Linq.Async”与 EFCore 一起使用会导致我的整个解决方案崩溃,因为对导入“System.Linq”和“Microsoft.EntityFrameworkCore”的文件中的所有 linq“.where”子句的引用不明确。已知问题请参阅:[以下方法或属性 (IAsyncEnumerable、IQueryable) #18220 之间的调用不明确](https://github.com/dotnet/efcore/issues/18220) AND [System.Interactive.Async 调用不明确引用 IX-Async 时出错 #18124](https://github.com/dotnet/efcore/issues/18124) (3认同)
  • @rytisk - 这是一个合理的评论,预计与在发布的半年内查看过此 SO 的超过 500 个用户中的很大一部分相关。使用“AsyncPageable&lt;T&gt;”(一个 MS Azure 库)的用户(碰巧也使用 MS EFCore)可以从我的评论中的免费信息中受益。这是我希望在遵循您发布的这个完全有效的答案的建议之前就知道的信息。回复:“你读过OP的问题了吗?” - 如果您想深入交谈,我可以聊天。 (3认同)

AAA*_*ddd 6

只需将您拥有的内容包装在扩展方法中即可。

// hrmmm, im not sure
public static async Task<T> FirstOrDefaultAsync<T>(this IAsyncEnumerable<T> enumerable)
{
   await foreach (var item in enumerable)
      return item;
   return default;
}

// This is more efficient 
public static async Task<T> FirstOrDefaultAsync2<T>(this IAsyncEnumerable<T> enumerable)
{
   var enumerator = enumerable.GetAsyncEnumerator();
   await enumerator.MoveNextAsync();
   return enumerator.Current;
}
Run Code Online (Sandbox Code Playgroud)

在这里检查他们的 IL

  • 更高效,部分原因是它没有遵守异步处理。 (2认同)