locked
ParallelFor bug RRS feed

  • Question

  • Prepare a static class, with a static property, static method, and a static constructor, then the bug comes:

    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);
            });
    
        }
    }

    call the property.

        static void Main(string[] args)
        {
            string str = ParallelForBug.StaticProperty;
            Console.WriteLine(str);            
        }

    You will never saw what the str is. Is this a bug, or just I miss anything.


    Mike Feng
    Help me, help you

    Tuesday, July 7, 2020 3:22 PM

Answers

  • Hi Mike Feng,

    Thank you for posting here.

    If you try to use 'Parallel.For' in the constructor, it seems that an exception will be thrown in the static constructor , so that you cannot get the value of 'StaticProperty'.

    As document says: If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running. Most commonly, a TypeInitializationException exception is thrown when a static constructor is unable to instantiate a type or for an unhandled exception occurring within a static constructor. For implicit static constructors that are not explicitly defined in source code, troubleshooting may require inspection of the intermediate language (IL) code.

    Avoid blocking the current thread in static constructors and initializers.

    Check following references:

    Static constructor deadlocks

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Wednesday, July 8, 2020 3:30 AM