DocumentClient CreateDocumentQuery async

时间:2016-09-05 21:55:53

标签: c# azure-cosmosdb

为什么没有CreateDocumentQuery的异步版本?

此方法例如可以是异步的:

    using (var client = new DocumentClient(new Uri(endpointUrl), authorizationKey, _connectionPolicy))
    {
        List<Property> propertiesOfUser =
            client.CreateDocumentQuery<Property>(_collectionLink)
                .Where(p => p.OwnerId == userGuid)
                .ToList();

        return propertiesOfUser;
    }

2 个答案:

答案 0 :(得分:16)

好查询,

只需尝试以下代码即可以异步方式使用。

DocumentQueryable.CreateDocumentQuery方法为集合下的文档创建查询。

 // Query asychronously.
using (var client = new DocumentClient(new Uri(endpointUrl), authorizationKey, _connectionPolicy))
{
     var propertiesOfUser =
        client.CreateDocumentQuery<Property>(_collectionLink)
            .Where(p => p.OwnerId == userGuid)
            .AsDocumentQuery(); // Replaced with ToList()


while (propertiesOfUser.HasMoreResults) 
{
    foreach(Property p in await propertiesOfUser.ExecuteNextAsync<Property>())
     {
         // Iterate through Property to have List or any other operations
     }
}


}

答案 1 :(得分:4)

基于Kasam Shaikh's answer我创建了ToListAsync扩展

  public static async Task<List<T>> ToListAsync<T>(this IDocumentQuery<T> queryable)
        {
            var list = new List<T>();
            while (queryable.HasMoreResults)
            {   //Note that ExecuteNextAsync can return many records in each call
                var response = await queryable.ExecuteNextAsync<T>();
                list.AddRange(response);
            }
            return list;
        }
        public static async Task<List<T>> ToListAsync<T>(this IQueryable<T> query)
        {
            return await query.AsDocumentQuery().ToListAsync();
        }

你可以使用它

var propertiesOfUser = await 
            client.CreateDocumentQuery<Property>(_collectionLink)
                .Where(p => p.OwnerId == userGuid)
                .ToListAsync()

请注意request to have CreateDocumentQuery async is open on github