动物名称是从 API 中获取的,如果未找到动物,该 API 可能会返回 404。但为了正确记录错误,我们需要访问动物的国家。是否可以?我读过something from a guy called Stephen Cleary这让我认为 lambda 是可能的,但我找不到任何东西。
var gettingNames = new List<Task<string>>();
foreach (var animal in animals)
{
gettingNames.Add(this.zooApi.GetNameAsync(animal));
}
try
{
await Task.WhenAll(gettingNames);
}
catch (Exception e)
{
var exception = gettingNames.Where(task => task.IsFaulted)
.SelectMany(x => x.Exception.InnerExceptions).First();
this.logger.LogError("The animal name from {Country} was not found",
animal.Country); // This is the goal
}
最佳答案
解决此问题的一种方法是投影每个 Animal
到 Task
它包含的信息比裸名称或裸错误更多。例如,您可以将其投影到 Task<ValueTuple<Animal, string, Exception>>
其中包含三条信息:动物,该动物的学名来自zooApi
,以及调用 zooApi.GetScientificNameAsync
时可能发生的错误方法。
进行此投影的最简单方法是 LINQ Select
运算符:
List<Task<(Animal, string, Exception)>> tasks = animals.Select(async animal =>
{
try
{
return (animal, await this.zooApi.GetScientificNameAsync(animal),
(Exception)null);
}
catch (Exception ex)
{
return (animal, null, ex);
}
}).ToList();
(Animal, string, Exception)[] results = await Task.WhenAll(tasks);
foreach (var (animal, scientificName, error) in results)
{
if (error != null)
this.logger.LogError(error,
$"The {animal.Name} from {animal.Country} was not found");
}
关于c# - 如何访问调用异步方法时可用的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69383186/