【发布时间】:2016-04-24 17:14:04
【问题描述】:
更新:
添加 TaskCreationOptions.LongRunning 解决了这个问题,但这是一个好方法吗?如果没有,克服此异常的最佳解决方案是什么?
我正在尝试解决一个问题。我已经实施了 StackOverFlow 中提供的建议,但这些建议并没有帮助解决问题。我通过附加扩展方法使用了其他替代方法,例如 ContinuwWith 选项而不是 Task.WaitAll。这也无济于事。
我已经放了 Ex.handle { } 并且我尝试在异常中的 Catch(aggrgateException ex) 中抛出 ex,但这无助于捕获实际异常。
我只安装了 .Net 4.0,所以我无法尝试使用 .Net 4.5 分辨率来解决这个问题
我一直得到的例外是
"System.AggregateException:" 通过等待任务或访问异常属性未观察到任务异常"
在此之后它只是杀死工作进程并且应用程序崩溃并且我在 EventViewer 中看到一个条目
这里的任何帮助将不胜感激。
我们有以下代码:
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)
}
try
{
Task.WaitAll(tasks);
}
catch (AggregateException e)
{
AddToLogFile("Exceptions thrown by WaitAll() : ");
for (int j = 0; j < e.InnerExceptions.Count; j++)
{
AddToLogFile(e.InnerExceptions[j].ToString());
}
}
catch(Exception ex)
{
AddToLogFile(ex.Message);
}
第二种选择
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()
}
【问题讨论】:
-
AggregateException的InnerException是什么? -
这是 System.Net.WebException :请求被中止。该请求在 System.Net.HTTPWebRequest.BeginGetRequestStream 处被取消......最后它在 System.Threading.Tasks.Task.Execute() 处说
-
这无关,但你不应该扁平化。只需登录 AggEx。这会记录最多的信息。
标签: c# exception task-parallel-library aggregate crash