Ignore the Tasks throwing Exceptions at Task.WhenAll and get only the completed results

后端 未结 3 1489
遥遥无期
遥遥无期 2021-02-19 01:17

I am working on a Task parallel problem that I have many Tasks that may or may not throw Exception.

I want to process all the tasks that finishes properly and log the re

3条回答
  •  我寻月下人不归
    2021-02-19 01:28

    You can get the result of each successfully completed Task from its property Result.

    var NormalTask1 = Task.FromResult("Task result 1");
    var NormalTask2 = Task.FromResult("Task result 2");
    var ExceptionTk = Task.FromException(new Exception("Bad Task"));
    
    Task[] tasks = new[] { NormalTask1, NormalTask2, ExceptionTk };
    Task whenAll = Task.WhenAll(tasks);
    try
    {
        await whenAll;
    }
    catch
    {
        if (whenAll.IsFaulted) // there is also the possibility of being canceled
        {
            foreach (var ex in whenAll.Exception.InnerExceptions)
            {
                Console.WriteLine(ex); // Log each exception
            }
        }
    }
    
    string[] results = tasks
        .Where(t => t.Status == TaskStatus.RanToCompletion)
        .Select(t => t.Result)
        .ToArray();
    Console.WriteLine($"Results: {String.Join(", ", results)}");
    

    Output:

    System.Exception: Bad Task
    Results: Task result 1, Task result 2

提交回复
热议问题