限制的執行區域Constrained Execution Regions

限制的執行區域 (CER) 是編寫可靠 Managed 程式碼的機制一部分。A constrained execution region (CER) is part of a mechanism for authoring reliable managed code. CER 定義一個區域,其中限制 Common Language Runtime (CLR) 擲回頻外例外狀況,而頻外例外狀況會防止執行區域中的整個程式碼。A CER defines an area in which the common language runtime (CLR) is constrained from throwing out-of-band exceptions that would prevent the code in the area from executing in its entirety. 在該區域內,使用者程式碼無法執行導致擲回頻外例外狀況的程式碼。Within that region, user code is constrained from executing code that would result in the throwing of out-of-band exceptions. PrepareConstrainedRegions 方法的前面必須緊接著 try 區塊,並將 catchfinallyfault 區塊標記為限制的執行區域。The PrepareConstrainedRegions method must immediately precede a try block and marks catch, finally, and fault blocks as constrained execution regions. 標記為限制的區域之後,程式碼只能呼叫具有強式可靠性合約的其他程式碼;而且,除非程式碼已準備好處理失敗,否則程式碼不應該配置非預期或不可靠的方法,或是對其進行虛擬呼叫。Once marked as a constrained region, code must only call other code with strong reliability contracts, and code should not allocate or make virtual calls to unprepared or unreliable methods unless the code is prepared to handle failures. CLR 會針對在 CER 中執行的程式碼延遲執行緒中止。The CLR delays thread aborts for code that is executing in a CER.

除了已標註的 try 區塊之外,限制的執行區域還會以不同的形式用於 CLR 中,值得注意的是在衍生自 CriticalFinalizerObject 類別的類別以及使用 ExecuteCodeWithGuaranteedCleanup 方法執行之程式碼中執行的重要完成項。Constrained execution regions are used in different forms in the CLR in addition to an annotated try block, notably critical finalizers executing in classes derived from the CriticalFinalizerObject class and code executed using the ExecuteCodeWithGuaranteedCleanup method.

CER 事先準備CER Advance Preparation

CLR 會事先準備 CER,以避免記憶體不足的情況。The CLR prepares CERs in advance to avoid out-of-memory conditions. 需要事先準備,讓 CLR 不會在 Just-In-Time 編譯或類型載入期間導致記憶體不足。Advance preparation is required so the CLR does not cause an out of memory condition during just-in-time compilation or type loading.

開發人員需要指出程式碼區域為 CER:The developer is required to indicate that a code region is a CER:


使用者只能使用他們以 CER 撰寫的程式碼類型。Users are constrained in the type of code they can write in a CER. 程式碼不會導致頻外例外狀況,例如可能是下列作業所導致:The code cannot cause an out-of-band exception, such as might result from the following operations:

  • 明確配置。Explicit allocation.

  • Boxing。Boxing.

  • 取得鎖定。Acquiring a lock.

  • 幾乎會呼叫未備妥的方法。Calling unprepared methods virtually.

  • 呼叫具有弱式或不存在可靠性合約的方法。Calling methods with a weak or nonexistent reliability contract.

在 .NET Framework 版本 2.0 中,這些條件約束是指導方針。In the .NET Framework version 2.0, these constraints are guidelines. 診斷是透過程式碼分析工具所提供。Diagnostics are provided through code analysis tools.

可靠性合約Reliability Contracts

ReliabilityContractAttribute 是一個自訂屬性,記載所指定方法的可靠性保證和損毀狀態。The ReliabilityContractAttribute is a custom attribute that documents the reliability guarantees and the corruption state of a given method.

可靠性保證Reliability Guarantees

可靠性保證是以 Cer 列舉值呈現,指出所指定方法的可靠性程度:Reliability guarantees, represented by Cer enumeration values, indicate the degree of reliability of a given method:

  • MayFail.MayFail. 在例外狀況下,此方法可能會失敗。Under exceptional conditions, the method might fail. 在此情況下,此方法會向呼叫端方法回報成功還是失敗。In this case, the method reports back to the calling method whether it succeeded or failed. 此方法必須包含在 CER 中,確保它可以報告傳回值。The method must be contained in a CER to ensure that it can report the return value.

  • None.None. 方法、類型或組件沒有 CER 的概念,而且很可能無法在 CER 內安全地呼叫,進而大幅降低狀態損毀。The method, type, or assembly has no concept of a CER and is most likely not safe to call within a CER without substantial mitigation from state corruption. 它不會利用 CER 保證。It does not take advantage of CER guarantees. 這具有如下表示:This implies the following:

    1. 在例外狀況下,此方法可能會失敗。Under exceptional conditions the method might fail.

    2. 此方法不一定會報告失敗。The method might or might not report that it failed.

    3. 不會寫入此方法來使用 CER,這是最常見案例。The method is not written to use a CER, the most likely scenario.

    4. 如果未將方法、類型或組件明確地識別為成功,則會將它隱含地識別為 NoneIf a method, type, or assembly is not explicitly identified to succeed, it is implicitly identified as None.

  • Success.Success. 在例外狀況下,此方法一定會成功。Under exceptional conditions, the method is guaranteed to succeed. 為了達到這個層級的可靠性,您應該一律建構所呼叫方法的 CER,即使是從非 CER 區域內呼叫它也是一樣。To achieve this level of reliability you should always construct a CER around the method that is called, even when it is called from within a non-CER region. 如果方法如預期完成,則方法會成功,但可以主觀檢視成功。A method is successful if it accomplishes what is intended, although success can be viewed subjectively. 例如,將 Count 標上 ReliabilityContractAttribute(Cer.Success) 表示在 CER 下執行時,一律會傳回 ArrayList 中的項目計數,而且絕不會讓內部欄位處於未定狀態。For example, marking Count with ReliabilityContractAttribute(Cer.Success) implies that when it is run under a CER, it always returns a count of the number of elements in the ArrayList and it can never leave the internal fields in an undetermined state. 不過,也會將 CompareExchange 方法標記為成功,並了解成功可能表示因競爭條件而無法將值取代為新值。However, the CompareExchange method is marked as success as well, with the understanding that success may mean the value could not be replaced with a new value due to a race condition. 重點在於此方法會依記載的運作方式運作,而且不需要寫入 CER 程式碼,以預期正確行為以外的任何異常行為,但不可靠程式碼看起來都一樣。The key point is that the method behaves in the way it is documented to behave, and CER code does not need to be written to expect any unusual behavior beyond what correct but unreliable code would look like.

損毀層級Corruption levels

損毀層級是以 Consistency 列舉值呈現,指出所指定環境中有多少狀態可能損毀:Corruption levels, represented by Consistency enumeration values, indicate how much state may be corrupted in a given environment:

  • MayCorruptAppDomain.MayCorruptAppDomain. 在例外狀況下,Common Language Runtime (CLR) 不保證目前應用程式定義域中的狀態一致性。Under exceptional conditions, the common language runtime (CLR) makes no guarantees regarding state consistency in the current application domain.

  • MayCorruptInstance.MayCorruptInstance. 在例外狀況下,保證此方法將狀態損毀限制為目前執行個體。Under exceptional conditions, the method is guaranteed to limit state corruption to the current instance.

  • MayCorruptProcess:在例外狀況下,CLR 不保證相關狀態一致性;亦即,此狀況可能會損毀處理序。MayCorruptProcess, Under exceptional conditions, the CLR makes no guarantees regarding state consistency; that is, the condition might corrupt the process.

  • WillNotCorruptState.WillNotCorruptState. 在例外狀況下,此方法一定不會損毀狀態。Under exceptional conditions, the method is guaranteed not to corrupt state.

可靠性 try/catch/finallyReliability try/catch/finally

可靠性 try/catch/finally 是一種例外狀況處理機制,且預測性保證的層級與未管理版本相同。The reliability try/catch/finally is an exception handling mechanism with the same level of predictability guarantees as the unmanaged version. catch/finally 區塊是 CER。The catch/finally block is the CER. 區塊中的方法需要事先準備,而且必須為不可中斷。Methods in the block require advance preparation and must be noninterruptible.

在 .NET Framework 版本 2.0 中,程式碼會透過在 try 區塊之前立即呼叫 PrepareConstrainedRegions,以通知執行階段 try 是可靠的。In the .NET Framework version 2.0, code informs the runtime that a try is reliable by calling PrepareConstrainedRegions immediately preceding a try block. PrepareConstrainedRegionsRuntimeHelpers 的成員,即編譯器支援類別。PrepareConstrainedRegions is a member of RuntimeHelpers, a compiler support class. 直接呼叫 PrepareConstrainedRegions 以透過編譯器暫止可用性。Call PrepareConstrainedRegions directly pending its availability through compilers.

不可中斷區域Noninterruptible Regions

不可中斷區域會將一組指示分組為 CER。A noninterruptible region groups a set of instructions into a CER.

在 .NET Framework 版本 2.0 中,透過編譯器支援暫止可用性,使用者程式碼會建立不可中斷區域,而此不可中斷區域具有在 PrepareConstrainedRegions 方法呼叫之前包含空 try/catch 區塊的可靠 try/catch/finally。In .NET Framework version 2.0, pending availability through compiler support, user code creates non-interruptible regions with a reliable try/catch/finally that contains an empty try/catch block preceded by a PrepareConstrainedRegions method call.

關鍵完成項物件Critical Finalizer Object

記憶體回收將執行完成項的 CriticalFinalizerObject 保證。A CriticalFinalizerObject guarantees that garbage collection will execute the finalizer. 配置時,會事先準備完成項和其呼叫歷程圖。Upon allocation, the finalizer and its call graph are prepared in advance. 完成項方法是在 CER 中執行,而且必須遵守 CER 和完成項的所有條件約束。The finalizer method executes in a CER, and must obey all the constraints on CERs and finalizers.

任何繼承自 SafeHandleCriticalHandle 的類型都一定會在 CER 內執行其完成項。Any types inheriting from SafeHandle and CriticalHandle are guaranteed to have their finalizer execute within a CER. SafeHandle 衍生類別中實作 ReleaseHandle,以執行釋放控制代碼所需的任何程式碼。Implement ReleaseHandle in SafeHandle derived classes to execute any code that is required to free the handle.

CER 中不允許的程式碼Code Not Permitted in CERs

CER 中不允許下列作業:The following operations are not permitted in CERs:

  • 明確配置。Explicit allocations.

  • 取得鎖定。Acquiring a lock.

  • Boxing。Boxing.

  • 多維陣列存取。Multidimensional array access.

  • 透過反映的方法呼叫。Method calls through reflection.

  • EnterLockEnter or Lock.

  • 安全性檢查。Security checks. 請不要執行要求,而是連結要求。Do not perform demands, only link demands.

  • COM 物件和 Proxy 的 IsinstCastclassIsinst and Castclass for COM objects and proxies

  • 取得或設定 Transparent Proxy 上的欄位。Getting or setting fields on a transparent proxy.

  • 序列化:Serialization.

  • 函式指標和委派。Function pointers and delegates.

另請參閱See also