When running this program, sometimes the exception has a stack trace which originated one the line that begins "throw new Exception...", but occasionally it has a stack trace which originates at the first curly bracket of the Parallel.For's delegate. Why would it have that line number?

I modified code to include System.Threading.Thread.CurrentThread.ManagedThreadId before e.ToString().
I had to run it about 20 times before I was able to reproduce it generating the exception on line 55.
From the output below, I can see that Goz was right; it was using the main thread (Thread ID 1) for some of the parallel tasks, but it had the right line number twice from the main thread and then the wrong number once from the main thread.
So still mysterious.

Note: I thought maybe there was some JIT compiling weirdness happening, but I confirmed that isn't the case by changing the parallel-for to call a static method with the same body, and then adding this attribute to that method: [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] So still a mystery.
–
AnssssssAug 14 '12 at 21:51

You say "The line number you are seeing...", but there are two line numbers I'm seeing. None of the exceptions are thrown from the main thread. If there were an exception thrown from the main thread, it would not be caught anywhere, I'm only catching exceptions within the lambda that the Parallel For's threads execute.
–
AnssssssSep 17 '12 at 15:29

not all iterations of a parallel.for run on a different thread. Some of the iterations run on the main/calling thread.
–
GozSep 17 '12 at 17:40

I tested it, and you're right, it was using the main thread some. However, your assumption about when the line number is correct wasn't always true. I was able to produce a case where the main thread reported the exception on line 55 (see edit to original post).
–
AnssssssSep 18 '12 at 19:41

That wouldn't result in sometimes reporting one line and sometimes reporting another within the scope of a single execution of the program.
–
ServyAug 14 '12 at 20:52

@Servy - The OP said, "sometimes the exception has a stack trace ...". He does not define when or how. Where are you getting that information from?
–
P.Brian.MackeyAug 14 '12 at 20:54

I looked at the code of his program, to see what it is doing, and the output. There is only one place where an exception is ever thrown, one place where it is logged, understandable code for how it is logged, and an output which indicates, as I said in my comment, that the stack trace is different for 7 of the 10 exceptions thrown from the same line, in the same program.
–
ServyAug 14 '12 at 20:57