如何在完成任务时处理任务 - 但每个任务都需要不同的方法来处理任务的结果

时间:2014-07-10 19:01:38

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

我正在使用async / await来调用几个外部API。所有这些都返回一个字符串值,但格式不同,需要自己处理。 我想在任务完成时处理返回的值。我不想等到所有完成后因此我正在使用Task.WhenAny()。如何完成任务并在完成每项任务时仍然使用正确的“过程”方法?

我在第一篇文章后做了一些修改,这是我最新的帖子:

public async Task<List<string>> Get()
{
    var task1 = Method1Async();
    var task2 = Method1Async();
    var tasks = new List<Task<string>> {task1, task2};
    var results = new List<string>();
    while (tasks.Count > 0)
    {
        var justCompletedTask = await Task.WhenAny(tasks);//will not throw
        tasks.Remove(justCompletedTask);
        try
        {
           var result = await justCompletedTask;
           results.Add(result);
        }
        catch(Exception)
        { 
          //deal with it
        }
    }

    return results;
}

private async Task<string> Method1Async()
{
    //this may throw - something like forbidden or any other exception
    var task = _httpClient.GetStringAsync("api1's url here");
    var result = await Method1ResultProcessorAsync(task);
    return result;
}

private async Task<string> Method1ResultProcessorAsync(Task<string> task)
{
    //process task's result -if it successuflly completed and return that
    return await task; //for now
}

private async Task<string> Method2Async()
{
    //this may throw - something like forbidden or any other exception
    var task = _httpClient.GetStringAsync("api2's url here");
    var result = await Method2ResultProcessorAsync(task);
    return await task;
}

private async Task<string> Method2ResultProcessorAsync(Task<string> task)
{
    //This processing logic is entirely different from Method1ResultProcessor
    //process task's result -if it successfully completed and return that 
    return await task; //for now
}

我在这里有两个问题:

  1. 这是解决问题的正确方法吗?
  2. 我如何更好地处理异常?这是非常重要的,所以一个人的失败不应该使整个事情失败。只要任何方法成功,就可以了。但如果全部失败,我想要抛出Get方法。

2 个答案:

答案 0 :(得分:1)

由于您的处理器方法已接受Task,您只需调用它们,它们将异步等待相应的结果:

public Task<string[]> Get()
{
    var task1 = Method1ResultProcessorAsync(Method1Async());
    var task2 = Method2ResultProcessorAsync(Method2Async());

    return Task.WhenAll(task1, task2);
}

按照你描述的方式处理异常将使这更复杂,但你可以使用类似的东西:

public async Task<List<string>> Get()
{
    var task1 = Method1ResultProcessorAsync(Method1Async());
    var task2 = Method2ResultProcessorAsync(Method2Async());

    var tasks = new[] { task1, task2 };

    try
    {
        await Task.WhenAll(tasks);
    }
    catch {}

    var results = tasks.Where(t => t.Status == TaskStatus.RanToCompletion)
                       .Select(t => t.Result)
                       .ToList();

    if (results.Any())
        return results;

    // or maybe another exception,
    // since await handles AggregateException in a weird way
    throw new AggregateException(tasks.Select(t => t.Exception));
}

答案 1 :(得分:0)

  1. 以下是描述Method1Async()Method2Async()的替代方法。这是ContinueWith的演示。回答你在标题中提出的问题 - 你可以为每个任务使用不同的方法,在任务完成后,该方法将被称为

    var task1 = _httpClient.GetStringAsync("api1's url here").ContinueWith(t => Method1ResultProcessorAsync(t));
    var task2 = _httpClient.GetStringAsync("api2's url here").ContinueWith(t => Method2ResultProcessorAsync(t));
    
  2. 您正确处理异常。回答&#34;但如果全部失败,我想要抛出Get方法。&#34;:只检查results.Count == 0之前returnthrow是否为0。