语言

Thread.BeginCriticalRegion 方法

定义

通知主机执行即将进入代码区域,其中线程中止或未经处理的异常的影响可能会危及应用程序域中的其他任务。

public:
 static void BeginCriticalRegion();
public static void BeginCriticalRegion();
static member BeginCriticalRegion : unit -> unit
Public Shared Sub BeginCriticalRegion ()

示例

以下示例演示如何使用 BeginCriticalRegion 和 EndCriticalRegion 方法将代码块划分为关键和非关键区域。

using System.Threading;

public class MyUtility
{
    public void PerformTask()
    {
        // Code in this region can be aborted without affecting
        // other tasks.
        //
        Thread.BeginCriticalRegion();
        //
        // The host might decide to unload the application domain
        // if a failure occurs in this code region.
        //
        Thread.EndCriticalRegion();
        //
        // Code in this region can be aborted without affecting
        // other tasks.
    }
}
open System.Threading

let performTask () =
    // Code in this region can be aborted without affecting
    // other tasks.
    //
    Thread.BeginCriticalRegion()
    //
    // The host might decide to unload the application domain
    // if a failure occurs in this code region.
    //
    Thread.EndCriticalRegion()
    //
    // Code in this region can be aborted without affecting
    // other tasks.
Imports System.Threading

Public Class MyUtility
    Public Sub PerformTask() 
        ' Code in this region can be aborted without affecting
        ' other tasks.
        '
        Thread.BeginCriticalRegion()
        '
        ' The host might decide to unload the application domain
        ' if a failure occurs in this code region.
        '
        Thread.EndCriticalRegion()
        ' Code in this region can be aborted without affecting
        ' other tasks.
    End Sub
End Class

注解

公共语言运行时(CLR)的主机(如 Microsoft SQL Server 2005)可以为代码关键和非关键区域中的故障建立不同的策略。 关键区域是线程中止或未经处理的异常的影响可能不限于当前任务。 相比之下,非关键代码区域中的中止或失败仅影响发生错误的任务。

例如,考虑在持有锁时尝试分配内存的任务。 如果内存分配失败,中止当前任务不足以确保该 AppDomain任务的稳定性,因为域中可能有其他任务等待同一锁。 如果当前任务已终止,则其他任务可能会死锁。

当故障发生在关键区域中时,主机可能会决定卸载整个 AppDomain ,而不是冒着继续执行可能不稳定的风险。 若要通知主机代码正在进入关键区域,请调用 BeginCriticalRegion。 执行返回到代码的非关键区域时调用 EndCriticalRegion 。

在SQL Server 2005 下运行的代码中使用此方法要求在最高主机保护级别运行代码。

适用于

另请参阅