【发布时间】:2023-03-28 13:55:01
【问题描述】:
我正在尝试执行以下场景:
- 创建多个任务
- 所有任务都在相同的结构中(相同的代码,不同的参数)
- 结构是:尝试做,如果失败则捕获,并抛出异常/异常
- 并行运行它们并等待它们完成
- 完成后,检查哪些任务抛出异常,哪些成功,没有抛出异常
public class Controller : ControllerBase
{
private readonly List<string> _names = new List<string>()
{
"name1",
"name2"
};
[HttpGet]
public async Task<ActionResult> Get()
{
// Leaving this processing because it is the same in the original code, maybe there is something here that is relevant
var tasks = _names.ToDictionary(name => name, name => ExecuteRequest(name, async (value) =>
{
return await ReturnOrThrow(value);
}));
// I want to wait until all were finished
await Task.WhenAll(tasks.Values); // This already throws an exception, i don't want it to
// I don't want to catch exception here and just ignore it
var namesThatSucceeded = tasks.Count(t => t.Value.IsCompletedSuccessfully);
var namesThatThrewException = tasks.Count(t => t.Value.IsFaulted);
return Ok(new
{
Succeeded = namesThatSucceeded,
Failed = namesThatThrewException
});
}
// The "generic task structure" that runs the request, catches exception if thrown, and re-throws it.
private async Task<string> ExecuteRequest(string name, Func<string, Task<string>> request)
{
try
{
return await request(name);
}
catch (HttpRequestException e)
{
Console.WriteLine(e.Message);
throw; // I would prefer to just return Faulted Task here so it won't throw exception
}
}
// The actual processing
private async Task<string> ReturnOrThrow(string name)
{
if (name == "name1")
{
throw new HttpRequestException();
}
return await Task.FromResult(name);
}
}
【问题讨论】:
-
您看到的异常是什么?
标签: c# asp.net-core exception async-await task