最近老是遇到bug,神烦。
第一步,构造这样的一个类:
public class ParallelForBug { public static string StaticProperty = "StaticProperty"; static void method(int i) { Console.WriteLine("null method: " + i); } static ParallelForBug() { Parallel.For(0, 10, i => { Console.WriteLine(i); method(i); }); } }
第二步,调用
string staticProperty = ParallelForBug.StaticProperty; Console.WriteLine(staticProperty);
但不幸的是,你将永远不会看到
Console.WriteLine(staticProperty)
的结果。Why???
在MSDN上问了这个问题,得到了一个回复,看起来这不是bug,是by design
详细文档如下:
devblogs.microsoft.com/pfxteam/static-constructor-deadlocks/
This CLR behavior is defined in section 10.5.3.3 of the ECMA CLI specification:
“Type initialization alone shall not create a deadlock unless some code called from a type initializer (directly or indirectly) explicitly invokes blocking operations.”
So, any operation that blocks the current thread in a static constructor potentially risks a deadlock. For example, just as waiting on threads can deadlock a static constructor, waiting on a task can have the same effect. And the same goes for Parallel.For, Parallel.ForEach, Parallel.Invoke, PLINQ queries, etc.
还是理解不深啊。