【发布时间】:2018-01-11 20:52:43
【问题描述】:
我假设我必须在下面的代码中使用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;
}
【问题讨论】:
-
@Dimi 不要等待方法。将他们的任务传递给变量并在
Task.WhenAll中调用它们 -
对不起,如果我说话天真,但为什么上面的代码不起作用?由于方法是
async,并且在每个异步调用上都使用await,所以if (calendar != null && workTypes != null)只会在前两个语句完成后执行。不是吗? -
不,我不认为有什么问题。当您有很多电话要拨打时,
Task.WhenAll是另一种选择。请参阅docs 中的这一行:“await 运算符应用于异步方法中的任务,以在方法的执行中插入暂停点,直到等待的任务完成。” -
代码可以以任何方式工作。不同之处在于它们的执行方式。在您的 OP 中,每个任务将一个接一个地执行。使用
Task.WhenAll,它们同时执行。 -
@crazyGamer 你是对的
标签: c# async-await task-parallel-library