简体   繁体   English

如何在 C# 中捕获任务异常

[英]How to catch Task exception in C#

I would like to catch all Task's exceptions of a batch of task, but I don't find the best solution.我想捕获一批任务的所有任务异常,但我没有找到最好的解决方案。 Maybe anyone can help me please?也许有人可以帮助我吗?

I have a function with the following declaration:我有一个具有以下声明的函数:

public async Task CreateBooking(CreateBookingModel createBookingModel)

In this method a throw exception can be do在这个方法中可以抛出异常

If I make a foreach like that:如果我这样做一个foreach:

foreach (DateTime day in EachDay(originalStartDate, originalEndDate))
{
    createBookingModel.StartDate = day;
    createBookingModel.EndDate = day;

    try
    {
        CreateBooking(createBookingModel);
    }
    catch (Exception ex)
    {
       raiseToTeams(ex, "Creation error");
    }
}

I don't received any else if the creation throw an exception.如果创建抛出异常,我不会收到任何其他信息。 I tried to make that:我试着这样做:

List<Task> tasks = new List<>();
foreach (DateTime day in EachDay(originalStartDate, originalEndDate))
{
    createBookingModel.StartDate = day;
    createBookingModel.EndDate = day;
    tasks.Add(CreateBooking(createBookingModel));              
}

try
{
    Task.WaitAll(tasks.toArray());
}
catch(AggregateException ex)
{
    ex.InnerExceptions.ForEach(subExp =>
    {
     if (subExp is ExternalBookingException)
     {
       raiseToTeams(subExp, "Creation error");
     }
    });
}

But I have 2 problems, if only one exception occurs no problem I catch it in the aggregation, if more that one I catch nothing even on a Exception and not a simple Aggregate catch.但是我有 2 个问题,如果只发生一个异常,我会在聚合中捕获它,如果更多,我什至在异常而不是简单的聚合捕获中什么也没有捕获。 And if each Task added before WaitAll() is finish, the line block infinitly, that I don't want !如果在 WaitAll() 之前添加的每个任务完成,该行无限地阻塞,我不想要!

Anybody have a solution plz?有人有解决方案吗?

Note, that注意

CreateBooking(createBookingModel);

just starts the Task and returns it.只是启动Task并返回它。 In order to get Task result you should await it:为了获得Task结果,您应该await它:

try
{
    // await - start task and await for its completion
    await CreateBooking(createBookingModel);
}
catch (Exception ex)
{
    raiseToTeams(ex, "Creation error");
}

Same if you have several tasks to complete:如果您有几项任务要完成,则相同:

List<Task> tasks = new List<>();

foreach (DateTime day in EachDay(originalStartDate, originalEndDate))
{
    createBookingModel.StartDate = day;
    createBookingModel.EndDate = day;
    tasks.Add(CreateBooking(createBookingModel));              
}

try
{
    // Note WhenAll instead of WaitAll
    // Note await
    await Task.WhenAll(tasks);
}
catch (Exception ex) // <- Note plain exception, not AggregatedException
{
  ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM