布尔在C#中执行Parallel.Foreach时包含任务已取消异常

时间:2017-08-11 10:36:22

标签: c# asp.net .net asp.net-mvc 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)

Code本身是一个简单而简单的Parallel.Foreach循环,其中包含如下逻辑:

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

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

@mortb这就是我记录stacktrace异常的方法:

  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 个答案:

没有答案