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.

    还是理解不深啊。

  • 相关阅读:
    RBAC概念
    Django框架的优缺点
    全文检索whoosh
    软件项目管理|期末复习(九)
    软件项目管理|期末复习(十四)
    HOJX 1003| Mixing Milk
    [转发]ACM刷题网站
    [转发]软件工具|Github上整理的一些工具
    软件项目管理|期末复习(三)
    计算机图形学|两道习题
  • 原文地址:https://www.cnblogs.com/crazyghostvon/p/ParallelForBug.html
Copyright © 2011-2022 走看看