.Net Core Async Await不会继续执行

时间:2017-12-07 15:21:03

标签: c# asp.net-core async-await

我有一个任务列表,它会调用Web服务。我在调用downloadTasksQuery.ToList()时开始执行它们。此时我想在完成每个任务时处理它们,并在完成后立即将距离添加到数据库。

当我在控制台中观看时。所有记录似乎都同时打印到控制台,我看到这行的输出。 Console.WriteLine(" Google Distance : " + d.google_distance);

它打印到控制台的次数是开始时的任务列表中的数字。

IEnumerable<Task<Distances>> downloadTasksQuery =
    (from tup in urlList select ProcessURL(tup));

List<Task<Distances>> downloadTasks = downloadTasksQuery.ToList();

while (downloadTasks.Count > 0)
{
    Task<Distances> thisFinished = await Task.WhenAny(downloadTasks);

    downloadTasks.Remove(thisFinished);
    try
    {
        Distances d = await thisFinished;
        if (d.has_error == false)
        {
            dr.Add(d);
        }
        else
        {
            dr.AddError(d);
        }
        Console.WriteLine(" Google Distance : " + d.google_distance);
    }
    catch (Exception e)
    {
        Console.WriteLine("Deleted task, did not save data");
    }
}
  

处理网址

private static async Task<Distances> ProcessURL(Tuple<string, int, string> tup)
{
    HttpClient client = new HttpClient();
    Distances d = new Distances();
    try
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
               //// Post is required by the web api
            var stringTask = client.PostAsync("https://website.com" + tup.Item1, new StringContent("null"));

            var msg2 = await stringTask.Result.Content.ReadAsStringAsync();
            d = FromXml<Distances>(msg2.Trim());

        }

    catch (Exception e)
        {
            d.has_error = true;
        }
    d.state_student_identifier = tup.Item3;
    d.student_transportation_id = tup.Item2;
    return d;
}

1 个答案:

答案 0 :(得分:0)

我建议使用ContinueWith,因为它似乎更适合您要做的事情:

var runningTasks = urlList.Select(tup => ProcessURL(tup)
    .ContinueWith(task =>
    {
        var d = task.Result;
        if (d.has_error)
            dr.AddError(d);
        else
            dr.Add(d);
        Console.WriteLine(" Google Distance : " + d.google_distance);
    }));
await Task.WhenAll(runningTasks);