Plinq 语句在静态构造函数内陷入僵局

发布于 2024-11-03 03:07:12 字数 352 浏览 1 评论 0原文

我遇到过这种情况,静态构造函数中的以下 plinq 语句陷入僵局:

static void Main(string[] args)
{
    new Blah();
}

class Blah
{
     static Blah()
     {
         Enumerable.Range(1, 10000)
            .AsParallel()
            .Select(n => n * 3)
            .ToList();
     }
}

仅当构造函数是静态时才会发生这种情况。 有人可以向我解释一下吗?

这是TPL错误吗?编译器?我?

I came across this situation where the following plinq statement inside static constructor gets deadlocked:

static void Main(string[] args)
{
    new Blah();
}

class Blah
{
     static Blah()
     {
         Enumerable.Range(1, 10000)
            .AsParallel()
            .Select(n => n * 3)
            .ToList();
     }
}

It happens only when a constructor is static.
Can someone explain this to me please.

Is it TPL bug? Compiler? Me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无风消散 2024-11-10 03:07:12

从静态构造函数调用线程代码通常是危险的。为了保证静态构造函数只执行一次,CLR在锁下执行静态构造函数。如果运行静态构造函数的线程等待辅助线程,则存在辅助线程由于某种原因也需要 CLR 内部锁的风险,并且程序将死锁。

下面是一个更简单的代码示例,演示了该问题:

using System.Threading;
class Blah
{
    static void Main() { /* Won’t run because the static constructor deadlocks. */ }

    static Blah()
    {
        Thread thread = new Thread(ThreadBody);
        thread.Start();
        thread.Join();
    }

    static void ThreadBody() { }
}

ECMA CLI 规范保证以下内容:

单独的类型初始化不会造成死锁,除非某些代码
从类型初始值设定项(直接或间接)显式调用
调用阻塞操作。

因此,只要静态构造函数中没有操作阻塞线程,类型初始值设定项(即静态构造函数)就不会死锁。如果静态构造函数确实阻塞,则存在死锁风险。

It is generally dangerous to call threading code from a static constructor. In order to ensure that the static constructor executes only once, the CLR executes the static constructor under a lock. If the thread running the static constructor waits on a helper thread, there is a risk that the helper thread is going to need the CLR-internal lock for some reason too, and the program will deadlock.

Here is a simpler code sample that demonstrates the problem:

using System.Threading;
class Blah
{
    static void Main() { /* Won’t run because the static constructor deadlocks. */ }

    static Blah()
    {
        Thread thread = new Thread(ThreadBody);
        thread.Start();
        thread.Join();
    }

    static void ThreadBody() { }
}

Section 10.5.3.3 "Races and deadlocks" of the ECMA CLI spec guarantees the following:

Type initialization alone shall not create a deadlock unless some code
called from a type initializer (directly or indirectly) explicitly
invokes blocking operations.

So, a type initializer (i.e., a static constructor) will not deadlock, provided that no operation in the static constructor blocks the thread. If the static constructor does block, it risks a deadlock.

叶落知秋 2024-11-10 03:07:12

虽然已经解释了为什么您不想在静态构造函数内进行线程工作,但我想我应该补充一点,“正确”的方法是使用 static Lazy。这也更加高效,因为生成这些资源的工作将被推迟到实际需要这些资源时。

class Blah
{
    // Supply factory method to generate the numbers, but actual generation will be deferred
    private static Lazy<List<int>> MyMagicNumbers = new Lazy<List<int>>(Blah.GenerateMagicNumbers);

    public void DoSomethingWithMagicNumbers()
    {
        // Call to Lazy<T>.Value will synchronize any calling threads until value is initially generated from the factory
        List<int> magicNumbers = Blah.MyMagicNumbers.Value;

        // ... do something here ...
    }

    private List<int> GenerateMagicNumbers()
    {
        return Enumerable.Range(1, 10000)
                          .AsParallel()
                          .Select(n => n * 3)
                          .ToList();
    }
}

While the reason has already been explained as to why you wouldn't want to do threaded work inside a static constructor, I thought I'd add that the "right" way to do this instead would be with a static Lazy<T>. This is also more efficient as the work to generate those resources will be defferred until those resources are actually needed.

class Blah
{
    // Supply factory method to generate the numbers, but actual generation will be deferred
    private static Lazy<List<int>> MyMagicNumbers = new Lazy<List<int>>(Blah.GenerateMagicNumbers);

    public void DoSomethingWithMagicNumbers()
    {
        // Call to Lazy<T>.Value will synchronize any calling threads until value is initially generated from the factory
        List<int> magicNumbers = Blah.MyMagicNumbers.Value;

        // ... do something here ...
    }

    private List<int> GenerateMagicNumbers()
    {
        return Enumerable.Range(1, 10000)
                          .AsParallel()
                          .Select(n => n * 3)
                          .ToList();
    }
}
小霸王臭丫头 2024-11-10 03:07:12

就其价值而言,Mono 上不会出现这个问题:

[mono] /tmp @ dmcs par.cs 
[mono] /tmp @ mono ./par.exe 

您是否有 Windows 编译的二进制文件,以便我可以比较生成的 MSIL?我不相信这是一个仅库问题,而且我很好奇:)


比较 IL 有点混乱,所以我决定在两个平台上尝试这两个二进制文件。
呵呵,我恢复了我的旧Windows虚拟机只是为了测试这个:)

在Mono上运行VS编译的二进制文件是没有问题的。您可以使用 2.10.1 (http://www.go-mono.com/mono-downloads/download.html) 在 Windows 上尝试,仅 77.4Mb :)

我在 linux 上使用了定制的 mono 2.11所以可能是功能支持尚未完成

     \ run on platform:      MS.Net 4.0      Mono 2.1x
built on: -------------+----------------------------------------
    Visual Studio       |      deadlock       no deadlock
                        |
    MonoDevelop         |      deadlock       no deadlock

我还注意到,在 Windows 上运行时,CTRL-C 能够打破锁定。
如果我找到更多相关内容,我会发布。


更新2

嗯,安装Mono 绕着安装VSExpress 运行,甚至在Windows 上也是如此。安装 mono 在 4 分钟内完成,结果是:

C:\Users\Seth>"c:\Program Files (x86)\Mono-2.10.1\bin\mono.exe" ConsoleApplication2.exe
C:\Users\Seth>

没有死锁:) 现在剩下的就是等待 VSExpress 安装(永远)和安装调试工具(未知),然后破解它(可能要等到深夜) 。再见

For what its worth, the issue does not arise on Mono:

[mono] /tmp @ dmcs par.cs 
[mono] /tmp @ mono ./par.exe 

Do you have a windows compiled binary so I can compare the generated MSIL? I'm not convinced this is a library-only issue, and I'm curious :)


Comparing the IL was a bit messy, so I decided to just try both binaries on both platforms.
Hehe I revived my old Windows virtual machine just to test this :)

Running the VS compiled binaries on Mono is no problem. You could try it on windows using 2.10.1 (http://www.go-mono.com/mono-downloads/download.html), only 77.4Mb :)

(I used a custom built mono 2.11 on linux so it could be that the feature support is not complete yet)

     \ run on platform:      MS.Net 4.0      Mono 2.1x
built on: -------------+----------------------------------------
    Visual Studio       |      deadlock       no deadlock
                        |
    MonoDevelop         |      deadlock       no deadlock

I also noticed that when running on windows, a CTRL-C is able to break out of the lock.
Will post if I find some more to this.


Update 2

Well, installing Mono runs circles around installing installing VSExpress even on windows. Installing mono has finished in 4 minutes, and resulted in:

C:\Users\Seth>"c:\Program Files (x86)\Mono-2.10.1\bin\mono.exe" ConsoleApplication2.exe
C:\Users\Seth>

No deadlock :) Now all that remains is waiting for VSExpress to be installed (forever) and istall debugging tools (unknown) and than have a crack at it (probably till late night). CU later

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文