当运行这个程序时,有时候这个异常有一个堆栈跟踪,它起源于一个开始“抛出新的异常...”的行,但偶尔它有一个堆栈跟踪,它起源于Parallel.For代表的第一个大括号。为什么会有这个行号?Parallel.For - 异常行号似乎是错的
using System.Collections.Concurrent;
using System.Threading.Tasks;
using System;
public class J
{
public static void Main()
{
ConcurrentDictionary<string, int> exceptions = new ConcurrentDictionary<string, int>();
Parallel.For(0, 10, (i, s) =>
{ //this is line 55
try
{
throw new Exception("blah"); //line 58
}
catch (Exception e)
{
string estring = e.ToString();
exceptions.TryAdd(estring, 0);
lock (exceptions)
{
exceptions[estring] += 1;
}
}
});
foreach (var entry in exceptions)
{
Console.WriteLine("==============" + entry.Value + " times");
Console.WriteLine(entry.Key);
}
}
}
这里是怪异的输出
==============3 times
System.Exception: blah
at J.<>c__DisplayClass5.<Main>b__4(Int32 i, ParallelLoopState s) in Program.cs:line 55
==============7 times
System.Exception: blah
at J.<>c__DisplayClass5.<Main>b__4(Int32 i, ParallelLoopState s) in Program.cs:line 58
Press any key to continue . . .
我修改后的代码,包括System.Threading.Thread.CurrentThread.ManagedThreadId e.ToString前()。 我必须运行它大约20次,然后才能重现它,并在第55行产生异常。 从下面的输出中,我可以看出Goz是正确的;它对一些并行任务使用主线程(线程标识1),但它的主线程有两个正确的行号,然后在主线程中有一次错误的号码。 所以仍然神秘。
==============3 times
5 - System.Exception: blah
at J.<>c__DisplayClass5.<Main>b__4(Int32 i, ParallelLoopState s) in Program.cs:line 58
==============1 times
6 - System.Exception: blah
at J.<>c__DisplayClass5.<Main>b__4(Int32 i, ParallelLoopState s) in Program.cs:line 58
==============2 times
1 - System.Exception: blah
at J.<>c__DisplayClass5.<Main>b__4(Int32 i, ParallelLoopState s) in Program.cs:line 58
==============1 times
1 - System.Exception: blah
at J.<>c__DisplayClass5.<Main>b__4(Int32 i, ParallelLoopState s) in Program.cs:line 55
==============2 times
4 - System.Exception: blah
at J.<>c__DisplayClass5.<Main>b__4(Int32 i, ParallelLoopState s) in Program.cs:line 58
==============1 times
3 - System.Exception: blah
at J.<>c__DisplayClass5.<Main>b__4(Int32 i, ParallelLoopState s) in Program.cs:line 58
Press any key to continue . . .
注意:我想也许有一些JIT编译奇怪发生,但我确认并非如此,通过更改parallel-for来调用具有相同主体的静态方法,然后将该属性添加到该方法: [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]所以还是个谜。 – Anssssss 2012-08-14 21:51:10
只要注意,[msdn社区问题](https://social.msdn.microsoft.com/Forums/en-US/f1e6988d-aeb4-4d2c-8f3f-e5eabad55a33/parallelfor-exception-line-number-in- stacktrace-seem-wrong?forum = parallelextensions)我问过去哪儿都没有,并且[Connect问题](https://connect.microsoft.com/VisualStudio/feedback/details/771771/parallel-for-exception-line-number-有时是错误的)我提交被标记为“不会解决”没有任何解释。 – Anssssss 2017-09-13 14:58:08