0

I have this shared function :

        public static async Task<IList<T>> ExecuteQueryAsync<T>(this CloudTable table, TableQuery<T> query, System.Threading.CancellationToken ct = default(System.Threading.CancellationToken), Action<IList<T>> onProgress = null) where T : ITableEntity, new()
    {

        var items = new List<T>();
        TableContinuationToken token = null;

        do
        {

            TableQuerySegment<T> seg = await table.ExecuteQuerySegmentedAsync<T>(query, token);
            token = seg.ContinuationToken;
            items.AddRange(seg);
            if (onProgress != null) onProgress(items);

        } while (token != null && !ct.IsCancellationRequested);

        return items;
    }

I normally would call this function like this

var query = new TableQuery<DynamicTableEntity>();
var res2 = await myTable.ExecuteQueryAsync(query);

which gives me IList

I'm trying to execute two simultaneous queries, but I'm very confused.

What I did so far

                List<Task> TaskList = new List<Task>();
                Task task1 = Task.Factory.StartNew( () =>
                {
                    return  table1.ExecuteQueryAsync(query);
                });


                Task task2 = Task.Factory.StartNew( () =>
                {
                    return  table2.ExecuteQueryAsync(query2);
                });

                Task.WaitAll(task1, task2);

                var res = ((Task<Task<IList<DynamicTableEntity>>>)task1).Result.Result ;

                var res2 = ((Task<Task<IList<DynamicTableEntity>>>)task2).Result.Result ;

It runs fine, but I'm not sure if it is the right approach ?

Any help would be greatly appreciated

2 Answers2

2

You don't want to use Task.Factory.StartNew (nor would the better Task.Run needed either), and you shouldn't use Task.WaitAll for asynchronous code.

Instead, ensure the method is marked as async, then just start the tasks, without awaiting, and then use await the result of Task.WhenAll

 var task1 = table1.ExecuteQueryAsync(query);
 var task2 = table2.ExecuteQueryAsync(query2);

 await Task.WhenAll(task1, task2);

 // Access the results of the completed Tasks here
StuartLC
  • 104,537
  • 17
  • 209
  • 285
1

If you use Task.WhenAll() you can await the result, avoiding .Result.Result. For example:

Task task1 = table1.ExecuteQueryAsync(query);

Task task2 = table2.ExecuteQueryAsync(query2);

var result = await Task.WhenAll(task1, task2);

var res = result[0];
var res2 = result[1];
8ytan
  • 300
  • 1
  • 7