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

Dev*_*per 1 c# task-parallel-library async-await

我假设我必须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;
        }
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 8

如果您希望同时执行这两个任务,那么请不要使用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;
}
Run Code Online (Sandbox Code Playgroud)

另请注意,您应该避免使用async void方法.

  • 用于指出`async void`的+1.最好返回`Task`对象,因为在调用它时你可以更好地控制执行. (2认同)