c# - 如何访问调用异步方法时可用的变量?

标签 c# exception async-await task-parallel-library

动物名称是从 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
}

最佳答案

解决此问题的一种方法是投影每个 AnimalTask它包含的信息比裸名称或裸错误更多。例如,您可以将其投影到 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/

相关文章:

java - Java异常: Using throws or try-catch

javascript - async/await 转换为 Promise.resolve 然后

c# - 如何将 MVVM 与 CRUD 操作一起使用?

c# - 从类库项目中的 App.config 中读取

c# - 了解 .NET 堆栈跟踪中的堆栈跟踪注释结尾

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

java - 通过将文件名附加到基本 URL 来从服务器目录读取文件

c# - 我如何使用 Json.NET 反序列化 PropertyInfo?

c# - 重载异步方法

javascript - 调用await jquery.ajax时如何获取数据、textStatus和jqXHR?