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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With