此代码在 t.Wait()
行无限期等待。
void Main()
{
Foo.Bar();
}
public static class Foo
{
static Foo()
{
var t = Task.Factory.StartNew (() => 1);
t.Wait();
"Done".Dump();
}
public static void Bar()
{
}
}
我希望任务立即运行并完成。关于为什么的任何想法?这似乎不会发生在实例构造函数中。 v4.42.01
最佳答案
代码的“StartNew
-and-Wait
”部分按预期工作(t.Result
将为 1
), 如果你把它放到 Main
或 Bar
方法中。它不会停止 Wait
-ing 仅当您将它放入静态构造函数时,因为“any operation that blocks the current thread in a static constructor potentially risks a deadlock”。
为了防止同时多次执行静态 ctors,CLR 在锁下执行它们。在这里,您尝试从 Foo 的静态构造函数调用 Foo 的匿名方法,并等待它完成,这会导致死锁。
关于c# - 任务和线程不在 Linqpad 的静态构造函数中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11087494/