Если вы хотите использовать TPL (Task Parallel Library) для асинхронного выполнения, вы можете использовать такой шаблон.
public static Task<IEnumerable<T>> ExecuteAsync<T>(DataServiceQuery<T> query, TableServiceContext tableContext)
{
List<T> values = null;
var cloudQuery = query.AsTableServiceQuery();
Func<ResultSegment<T>, Task<ResultSegment<T>>> getSegment = null;
getSegment = new Func<ResultSegment<T>, Task<ResultSegment<T>>>((previous) =>
{
return ExecuteSegmentAsync(cloudQuery, previous).ContinueWith(exec =>
{
if (exec.IsFaulted || exec.IsCanceled)
{
return exec;
}
else
{
var segment = exec.Result;
if(segment.HasMoreResults)
{
if(values == null)
{
values = new List<T>();
}
values.AddRange(segment.Results);
return getSegment(segment);
}
else
{
return exec;
}
}
}).Unwrap();
});
return getSegment(null).ContinueWith(exec =>
{
exec.ThrowOnError("ExecuteAsync");
var segment = exec.Result;
if(values == null)
{
return segment.Results;
}
else
{
values.AddRange(segment.Results);
return values;
}
});
}
private static Task<ResultSegment<T>> ExecuteSegmentAsync<T>(CloudTableQuery<T> query, ResultSegment<T> previous)
{
var tcs = new TaskCompletionSource<ResultSegment<T>>();
RetryPolicy.ExecuteAction(ac =>
{
// Invoke the begin method of the asynchronous call.
if(previous != null)
{
query.BeginExecuteSegmented(previous.ContinuationToken, ac, null);
}
else
{
query.BeginExecuteSegmented(ac, null);
}
},
ar =>
{
// Invoke the end method of the asynchronous call.
return query.EndExecuteSegmented(ar);
},
values =>
{
tcs.SetResult(values);
},
ex =>
{
// Async opetation failed after multiple retries
tcs.SetException(ex);
});
return tcs.Task;
}