如何使用单个'await Task.WhenAll'简化多个等待?

时间:2017-08-04 03:47:36

标签: c# async-await task-parallel-library

我认为我必须在下面的代码中使用Task.WhenAll,但无法弄清楚它应该正确实现。

请帮助。

 public async void UpdateData()
        {
            var month = (cbMonths.SelectedItem as MonthView).ID;
            var year = (cbYears.SelectedItem as YearView).ID;
            var deviceTypeID = (int)DeviceType;
            var calendar = await GetCalendar(month, year, deviceTypeID);
            var workTypes = await GetWorkTypes(); 

            if (calendar != null && workTypes != null) // Task.WhenAll ???
            {
                //...
            }
        }


 private async Task<List<WorkTypeItem>> GetWorkTypes()
        {
            try
            {
                HttpClient client = new HttpClient();

                var url = Properties.Settings.Default.ServerBaseUrl + @"/api/staff/WorkTypes";

                HttpResponseMessage response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)    // Check the response StatusCode
                {
                    var serSettings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All };    
                    string responseBody = await response.Content.ReadAsStringAsync();

                    return JsonConvert.DeserializeObject<List<MSOCommon.WorkTypeItem>>(responseBody, serSettings); 
                }              
                else
                {
                    logger.Error(Properties.Resources.DATACannotGetWorkTypes);
                }
            }
            catch (Exception ex)
            {
                logger.Error(Properties.Resources.DATACannotGetWorkTypes + " " + ex.Message);
            }

            return null;
        }

2 个答案:

答案 0 :(得分:7)

如果您希望同时执行这两项任务,那么请不要p1 = ''' Electronic commerce, commonly written as E-Commerce, is the trading or facilitation of trading in goods or services using computer networks, such as the Internet or online social networks. Electronic commerce draws on technologies such as mobile commerce, electronic funds transfer, supply chain management, Internet marketing, online transaction processing, electronic data interchange (EDI), inventory management systems, and automated data collection systems. '''.split() p2 = ''' Modern electronic commerce typically uses the World Wide Web for at least one part of the transaction's life cycle although it may also use other technologies such as e-mail. The benefits of e-commerce include it’s the speed of access, a wider selection of goods and services, accessibility, and international reach. '''.split() print(set(p1).intersection(p2)) {'and', 'the', 'technologies', 'of', 'electronic', 'such', 'commerce', 'as', 'goods'} 这些方法。而是将他们的任务传递给变量并在await

中调用它们
Task.WhenAll

另请注意,您应该避免使用public async Task UpdateData() { var month = (cbMonths.SelectedItem as MonthView).ID; var year = (cbYears.SelectedItem as YearView).ID; var deviceTypeID = (int)DeviceType; var task1 = GetCalendar(month, year, deviceTypeID); var task2 = GetWorkTypes(); await Task.WhenAll(task1, task2); var calendar = task1.Result; var workTypes = task2.Result; } 方法。

答案 1 :(得分:2)

        var calendarTask = GetCalendar(month, year, deviceTypeID);
        var workTypesTask = GetWorkTypes(); 

        Task.WaitAll(calendarTask, workTypesTask);
        var calendar = await calendarTask;
        var workTypes = await workTypesTask;

要回答@crazyGamer,您这样做的原因是两个任务可以同时运行。否则,在你开始工作之前,你还在等待第一项任务。当然,如果他们互相依赖,这是件好事。否则,这将在MP系统上运行得更快。