This code waits indefinitely on the t.Wait()
line.
void Main()
{
Foo.Bar();
}
public static class Foo
{
static Foo()
{
var t = Task.Factory.StartNew (() => 1);
t.Wait();
"Done".Dump();
}
public static void Bar()
{
}
}
I would expect the task to run and finish immediately. Any thoughts as to why? This doesn't seem to happen in instance constructors. v4.42.01
The "StartNew
-and-Wait
" part of your code works as expected (t.Result
will be 1
), if you put it into the Main
or into the Bar
method. It doesn't stop Wait
-ing only if you put it into the static constructor, because "any operation that blocks the current thread in a static constructor potentially risks a deadlock".
In order to prevent executing static ctors multiple times concurrently, the CLR executes them under a lock. Here you try to call an anonymous method of Foo, and wait for it to finish, from the static ctor of Foo, which causes a deadlock.