User987
User987

Reputation: 3823

Boolean Include Task Canceled Exception while doing Parallel.Foreach in C#

I have an odd situation where I'm not able to locate the source of my error for the following stacktrace:

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)

The Code itself is a plain and simple Parallel.Foreach loop with some logic like following:

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

What could be the source of this issue ? Do you guys have any tips for me where should I look for?

@mortb this is how I log the stacktrace exception:

  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);
            }

Upvotes: 1

Views: 3084

Answers (2)

mortb
mortb

Reputation: 9849

Proposed changes to logging:

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);
      }
}

Upvotes: 1

Nitram
Nitram

Reputation: 6716

Your // code inside is throwing a exception. The exception you see is the Parallel.For loop killing its worker tasks to shutdown properly. Normally the ForEach function should throw a exception in the end that holds the actual reason for the error. The error you see looks like the debugger triggering on a inner exception of the ForEach function.

Upvotes: 1

Related Questions