當運行這個程序時,有時候這個異常有一個堆棧跟蹤,它起源於一個開始「拋出新的異常...」的行,但偶爾它有一個堆棧跟蹤,它起源於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