• 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.

    还是理解不深啊。

  • 相关阅读:
    eclipse 配置SVN代理服务器
    jenkins 配置SVN 代理服务器
    记录服务器启动redis过程
    java牛客刷题2020年9月4日
    java牛客网错题2020年9月3日
    bootstrap-select 实现搜索,如果内容搜索不到显示到框内
    pandas教程5-合并 concat
    pandas教程-4导入导出
    pandas简单教程1
    AttributeError: module 'pandas' has no attribute 'Series'
  • 原文地址:https://www.cnblogs.com/crazyghostvon/p/ParallelForBug.html
Copyright © 2020-2023  润新知