Skip to main content
 首页 » 编程设计

c#之任务和线程不在 Linqpad 的静态构造函数中运行

2024年02月20日15lovecherry

此代码在 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 的匿名方法,并等待它完成,这会导致死锁。

相关 SO 页面:1 , 2