Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.Wait() never returns when called during initialization of static field?

Tags:

c#

task

I have the following simple code:

    class Program
    {
        public static readonly List<int> Years = BuildList();

        static void Main(string[] args) { }

        private static List<int> BuildList()
        {
            var t = Task.Run(() => x());
            t.Wait();
            return new List<int>();
        }

        private static void x()
        {
            Console.WriteLine("Hello World");
        }
    }

After debugging, x() is never entered and t.Wait() never completes / returns and hangs forever. Can anyone explain this bizarre behavior?

It's not like there are any UI blocking calls, all I can guess is that the threadpool is somehow maxed out?

If I remove the .Wait() call, then x() does eventually get entered.

Note that calling BuildList() from Main works perfectly fine.

like image 581
maxp Avatar asked Dec 15 '22 01:12

maxp


1 Answers

Inside the static initializer for Program you're starting a new thread and having it call a method on the class that you are currently running the static initializer for. C# will ensure that a class is initialized exactly once, so if two threads try to initialize a class then one will wait for the other to finish. Since the initializer is waiting for x to finish before it can continue, and x is waiting for the initializer to finish before it can run, you have a deadlock.

like image 51
Servy Avatar answered Dec 17 '22 02:12

Servy