Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 异步任务上的异常处理_C# - Fatal编程技术网

C# 异步任务上的异常处理

C# 异步任务上的异常处理,c#,C#,我用它作为参考 public async Task DoWork() { int[] ids = new[] { 1, 2, 3, 4, 5 }; await Task.WhenAll(ids.Select(i => DoSomething(1, i, blogClient))); } 是否可以捕获特定索引上的异常。如中所示,当DoSomething在i上抛出异常时,我可以捕获该特定索引?一种简单的方法是捕获异常,在异常数据上插入索引信息,然后重试: int[] ids

我用它作为参考

public async Task DoWork() {

    int[] ids = new[] { 1, 2, 3, 4, 5 };
    await Task.WhenAll(ids.Select(i => DoSomething(1, i, blogClient)));
}

是否可以捕获特定索引上的异常。如中所示,当DoSomething在i上抛出异常时,我可以捕获该特定索引?

一种简单的方法是捕获异常,在异常数据上插入索引信息,然后重试:

int[] ids = new[] {1, 2, 3, 4, 5};
await Task.WhenAll(ids.Select(i =>
{
    try
    {
        return DoSomething(1, i, null);
    }

    catch (Exception ex)
    {
        ex.Data["FailedIndex"] = i; // Information about failed index
        throw;
    }
}));

一种简单的方法是捕获异常,插入异常数据的索引信息,然后重新浏览:

int[] ids = new[] {1, 2, 3, 4, 5};
await Task.WhenAll(ids.Select(i =>
{
    try
    {
        return DoSomething(1, i, null);
    }

    catch (Exception ex)
    {
        ex.Data["FailedIndex"] = i; // Information about failed index
        throw;
    }
}));

如果没有,您可以让您的单个DoSomething函数将索引作为数据的一部分引发异常,然后在DoWork级别捕获它。如果没有,您可以让您的单个DoSomething函数将索引作为数据的一部分引发异常,然后在定位销级别捕获它,可能是