2017-08-11 66 views
0

我有一个奇怪的情况下,我无法找到我的错误的根源以下堆栈跟踪:布尔包括任务取消的异常而在C#做Parallel.Foreach

Message :One or more errors occurred.<br/> 
StackTrace : at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) 
    at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) 
    at System.Threading.Tasks.Task.Wait() 
    at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally) 
    at System.Threading.Tasks.Parallel.For(Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body) 

代码本身是有一些逻辑简单明了Parallel.Foreach循环像下面:

Parllel.Foreach(_collection, new ParallelOptions { MaxDegreeOfParallelism =5 }, item=> 
{ 
// code inside 
}); 

可能是什么这个问题的根源?你们有什么提示给我,我应该在哪里寻找?

@mortb这是我的日志堆栈跟踪异常:

string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Error.txt"; 

      using (StreamWriter writer = new StreamWriter(filePath, true)) 
      { 
       writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + 
        "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); 
       writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); 
      } 
+0

调试,并采取一看抛出的异常属性'InnerExceptions'(注意'InnerExceptions'的S)外的例外是刚刚超过一个的包装或几个抛出异常通过''// code inside''“,实际的异常被列在'InnerExceptions'中 – mortb

+0

@mortb这就是我的错误..我无法将异常写入文本文件...等待我将显示你我如何记录错误.. – User987

+0

@mortb你能看到我更新的问题吗?这就是我如何登录异常本身...有没有什么办法可以记录内部异常本身并查看哪条线会抛出它? – User987

回答

1

建议更改日志:

string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Error.txt"; 

using (StreamWriter writer = new StreamWriter(filePath, true)) 
{ 
     foreach(var inner in (ex as AggregateException).?InnerExceptions ?? (new [] {ex})) 
     { 
      writer.WriteLine("Message :" + inner.Message + "<br/>" + Environment.NewLine + "StackTrace :" + inner.StackTrace + 
      "" + Environment.NewLine + "Date :" + DateTime.Now.ToString()); 
      writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); 
     } 
} 
+0

Mortb,非常感谢你!要现在尝试代码:) – User987

+0

它说的前。不包含名为InnerExceptions的属性,而只是一个名为“InnerException”的单值形式的属性 – User987

+0

可能你已经发现异常为catch(Exception ex),然后它已经失去了它的类型,我添加了代码将它转换为AggregateException (未测试)代码不是最佳的,但它可能工作 – mortb

1

// code inside抛出一个异常。你看到的例外是Parallel.For循环,它的工作任务正常关闭。通常,ForEach函数应该在最后引发异常,以确定错误的实际原因。您看到的错误看起来像调试器触发ForEach函数的内部异常。

+0

非常感谢您的回复!我更新了我最初的问题,我如何登录异常本身...有什么办法可以记录内部异常本身? – User987

+0

异常的类型应该是'AggregateException'。如果你投射到这一个,你会得到一个属性'InnerExceptions'(注意“s”)。此列表中的一个例外是您正在查找的那个例外。 – Nitram