using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.Table.Queryable;
namespace AzureTableStorage.TableQueryAsync
{
public static class TableQueryExtensions
{
/// <summary>
///
/// </summary>
/// <param name="tableQuery"></param>
/// <param name="ct"></param>
public async static Task<IEnumerable<TElement>> ExecuteAsync<TElement>(this TableQuery<TElement> tableQuery, CancellationToken ct)
{
var nextQuery = tableQuery;
var continuationToken = default(TableContinuationToken);
var results = new List<TElement>();
do
{
var queryResult = await nextQuery.ExecuteSegmentedAsync(continuationToken, ct);
results.Capacity += queryResult.Results.Count;
results.AddRange(queryResult.Results);
continuationToken = queryResult.ContinuationToken;
if (continuationToken != null && tableQuery.TakeCount.HasValue)
{
var itemsToLoad = tableQuery.TakeCount.Value - results.Count;
nextQuery = itemsToLoad > 0
? tableQuery.Take<TElement>(itemsToLoad).AsTableQuery()
: null;
}
} while (continuationToken != null && nextQuery != null && !ct.IsCancellationRequested);
return results;
}
}
}