System.Threading.Tasks.TaskExceptionHolder.Finalize()中的System.AggregateException

时间:2016-04-24 17:14:05

标签: c# exception task-parallel-library aggregate crash

更新

添加TaskCreationOptions.LongRunning解决了这个问题,但这是一个好方法吗?如果没有,那么克服此异常的最佳解决方案是什么?

我正在尝试排查问题。我已经实现了StackOverFlow中提供的建议,但这些建议没有帮助解决问题。我通过附加扩展方法使用了其他替代方法,如ContinuwWith选项而不是Task.WaitAll。这也没有帮助。

我已经放了Ex.handle {}并且我在异常中尝试了在Catch(aggrgateException ex)中抛出ex,但这并没有帮助捕获实际的异常。

我只安装了.Net 4.0,所以我无法尝试.Net 4.5分辨率来解决这个问题

我一直在获得的例外是

  

“System.AggregateException:”通过等待任务或访问Exception属性未观察到任务的异常“

在此之后,它只会杀死工作进程,应用程序崩溃,我在EventViewer中看到一个条目

这里的任何帮助将不胜感激。

我们有以下代码:

public Static Class Extensions
{
 public static void LogExceptions(this Task<List<<MyBusinessObject>> task)
        {
            task.ContinueWith(t =>
            {
                var aggException = t.Exception.Flatten();
                foreach (var exception in aggException.InnerExceptions)
                {
                    AddToLogFile("Task Exception: " + exception.Message);

                }
            },
            TaskContinuationOptions.OnlyOnFaulted);
        }
}
//In a different class call the extension method after starting the new tasks
Task<List<MyBusinessObject>>[] tasks = new Task<List<MyBusinessObject>>[MyCollection.Count];

for (int i = 0; i < MyCollection.Count; i++)
{
    MyDTO dto = new MyDTO();

     --Some Property Assignment for the MyDTO object--

    tasks[i] = Task<List<MyBusinessObject>>.Factory.StartNew(MyDelegate, dto).LogExceptions()

}

第二选择

docker run -it [public dockerhub name]

1 个答案:

答案 0 :(得分:0)

我不是一次为每个迭代创建一个新任务,而是每次都为100个任务创建新任务。然后我等待所有任务完成并再完成100个任务,直到所有任务完成

int count = Mycollection.Count();                     任务&gt; []任务;

        int i = 0;
                int j;
                while (i < count)
                {
                    j = 0;
                    tasks = new Task<List<MyBusinessObject>>[nbrOfTasks];
                    foreach (var p in Mycollection.Skip(i).Take(nbrOfTasks))
                    {
                        MyRequestDto dto = new MyRequestDto ();
                    --Some Proerty Assignment
                        tasks[j] = Task<List<MyBusinessObject>>.Factory.StartNew(MyDelegate, dto);
                        i++;
                        j++;
                    }

        try
                    {
                        // Wait for all the tasks to finish. 
                        if (tasks != null && tasks.Count() > 0)
                        {
                            tasks = tasks.Where(t => t != null).ToArray();
                            Task.WaitAll(tasks);
                        }
                    }
        catch (AggregateException e)
                    {
            }       

这与可用于维护多个任务的内存有关。如果所需的RAM无法在此过程中为并发任务提供服务,那么应用程序就会崩溃。这就是为什么最好生成有限的任务。而不是吐出多个并将其留给线程池进行管理。

相关问题