CAN C#“是”经营者在释放模式优化遭受基于.NET 4? [英] Can C# 'is' operator suffer under release mode optimization on .NET 4?

查看:128
本文介绍了CAN C#“是”经营者在释放模式优化遭受基于.NET 4?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个简单的测试夹具。它成功地调试版本,未能在发布版本(VS2010,.NET4的解决方案,64):

Below is a simple test fixture. It succeeds in Debug builds and fails in Release builds (VS2010, .NET4 solution, x64):

[TestFixture]
public sealed class Test
{
    [Test]
    public void TestChecker()
    {
        var checker = new Checker();
        Assert.That(checker.IsDateTime(DateTime.Now), Is.True);
    }
}

public class Checker
{
    public bool IsDateTime(object o)
    {
        return o is DateTime;
    }
}



这似乎代码的优化造成十分严重的破坏一些;如果我禁用它的发布版本,它的工作原理也是如此。这是相当令人费解给我。下面,我用ILDASM拆卸2版本的构建:

It seems code optimization wreaks some havoc; if I disable it on the Release build, it works as well. That was rather puzzling to me. Below, I've used ILDASM to disassemble the 2 versions of the build:

调试IL:

.method public hidebysig instance bool IsDateTime(object o) cil managed
{
  // Code size       15 (0xf)
  .maxstack  2
  .locals init (bool V_0)
  IL_0000:  nop
  IL_0001:  ldarg.1
  IL_0002:  isinst     [mscorlib]System.DateTime
  IL_0007:  ldnull
  IL_0008:  cgt.un
  IL_000a:  stloc.0
  IL_000b:  br.s       IL_000d
  IL_000d:  ldloc.0
  IL_000e:  ret
} // end of method Validator::IsValid

释放IL:

.method public hidebysig instance bool IsDateTime(object o) cil managed
{
  // Code size       10 (0xa)
  .maxstack  8
  IL_0000:  ldarg.1
  IL_0001:  isinst     [mscorlib]System.DateTime
  IL_0006:  ldnull
  IL_0007:  cgt.un
  IL_0009:  ret
} // end of method Validator::IsValid

这似乎是一个存储和负载优化掉。针对早期版本的.NET框架使问题消失,但是这可能只是一个侥幸。我觉得这种行为有点令人不安,任何人可以解释为什么编译器会认为它是安全的这样做会产生不同的观察行为的优化?

It seems a store and load is optimized away. Targeting earlier versions of the .NET framework made the problem go away, but that may just be a fluke. I found this behaviour somewhat unnerving, can anybody explain why the compiler would think it safe to do an optimization that produces different observable behaviour?

先谢谢了。

推荐答案

这个错误已经的这个SO雅各斯坦利质疑。雅各布已经拥有的报告的错误的,微软已经确认它的确是在CLR JIT的错误。微软是这样说的:

This bug already came up in this SO question by Jacob Stanley. Jacob has already reported the bug, and Microsoft has confirmed that it is indeed a bug in the CLR JIT. Microsoft had this to say:

这bug会被固定在运行时的未来版本。恐怕这是为时过早,如果这将是一个服务包或下一个主要版本。

This bug will be fixed in a future version of the runtime. I'm afraid it's too early to tell if that will be in a service pack or the next major release.

再次感谢您报告了该问题。

Thank you again for reporting the issue.

您应该能够通过将以下属性 TestChecker()来解决这个bug

You should be able to work around the bug by adding the following attribute to TestChecker():

[MethodImpl(MethodImplOptions.NoInlining)]

这篇关于CAN C#“是”经营者在释放模式优化遭受基于.NET 4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆