本文介绍了对特定功能或代码块(C#)禁用编译器优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器在优化RELEASE版本方面做得很出色,但有时它对于确保关闭局部功能(而不是通过取消选中Project Options > Optimize code而不是整个项目)的优化可能很有用.

The compiler does a great job of optimising for RELEASE builds, but occasionally it can be useful to ensure that optimisation is turned off for a local function (but not the entire project by unticking Project Options > Optimize code).

在C ++中,这可以通过以下方式(通常将#pragma注释掉)来实现:

In C++ this is achieved using the following (with the #pragma normally commented out):

#pragma optimize( "", off )
// Some code such as a function (but not the whole project)
#pragma optimize( "", on )

C#中是否有等效项?

Is there an equivalent in C#?

几个很好的答案建议用MethodImplOptions.NoOptimization装饰该方法.这是在.NET 3.5中实现的,尽管未在Compact Framework(CF)版本中实现.一个相关的后续问题是:是否等同于

Several excellent answers suggest decorating the method with MethodImplOptions.NoOptimization. This was implemented in .NET 3.5, though not in the Compact Framework (CF) version. A related follow-on question is whether an equivalent for:

* projects targeting .NET 3.0 or earlier?
* projects deployed to a device such as Windows CE 6.0 using the .NET 3.5 CF?

推荐答案

您可以用[MethodImpl(MethodImplOptions.NoOptimization)][MethodImpl(MethodImplOptions.NoInlining)]装饰特定的方法(或属性getter/setter),这将阻止JITter优化和内联方法:

You can decorate a specific method (or a property getter/setter) with [MethodImpl(MethodImplOptions.NoOptimization)] and [MethodImpl(MethodImplOptions.NoInlining)], this will prevent the JITter from optimizing and inlining the method:

[MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
private void MethodWhichShouldNotBeOptimized()
{ }

但是,没有办法将此属性应用于代码块.在.NET 3.5中还添加了NoOptimization属性,这对于旧版代码或Compact Framework可能很重要.

However, there isn't a way to apply this attribute to a block of code. Also NoOptimization attribute was added in .NET 3.5, which might be important for legacy code or Compact Framework.

这篇关于对特定功能或代码块(C#)禁用编译器优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 08:27