如何在C#中等待多个异步任务?

时间:2019-06-20 09:22:26

标签: c#

我有这个共享功能:

        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;
    }

我通常会这样调用该函数

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

这给了我IList

我试图同时执行两个查询,但是我很困惑。

我到目前为止所做的

                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 ;

它运行正常,但是我不确定这是否正确吗?

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:2)

您不想使用Task.Factory.StartNewbetter Task.Run也不需要),并且您不应该将Task.WaitAll用于异步代码。

相反,请确保该方法被标记为async,然后仅在不等待的情况下启动任务,然后使用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

答案 1 :(得分:1)

如果使用Task.WhenAll(),则可以等待结果,避免使用.Result.Result。例如:

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];