zoukankan      html  css  js  c++  java
  • Parallel For Bug in static constructor

    最近老是遇到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.

    还是理解不深啊。

  • 相关阅读:
    VUE 入门基础(8)
    VUE 入门基础(7)
    VUE 入门基础(6)
    VUE 入门基础(5)
    VUE 入门基础(4)
    VUE 入门基础(3)
    线程的通信
    如何实现一个简单的RPC
    Java程序员必须掌握的线程知识-Callable和Future
    同步函数死锁现象
  • 原文地址:https://www.cnblogs.com/crazyghostvon/p/ParallelForBug.html
Copyright © 2011-2022 走看看