SafeHandle.ReleaseHandle 方法

定義

在衍生類別中覆寫時,執行釋放控制代碼所需的程式碼。

protected:
 abstract bool ReleaseHandle();
protected abstract bool ReleaseHandle ();
abstract member ReleaseHandle : unit -> bool
Protected MustOverride Function ReleaseHandle () As Boolean

傳回

如果成功釋放控制代碼,則為 true;如果發生嚴重失敗的事件,則為 false。 在這種情況下,它會產生 releaseHandleFailed Managed 偵錯助理。

範例

下列程式代碼範例會釋放句柄,而且是類別所提供較大範例的 SafeHandle 一部分。

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
override protected bool ReleaseHandle()
{
    // Here, we must obey all rules for constrained execution regions.
    return NativeMethods.CloseHandle(handle);
    // If ReleaseHandle failed, it can be reported via the
    // "releaseHandleFailed" managed debugging assistant (MDA).  This
    // MDA is disabled by default, but can be enabled in a debugger
    // or during testing to diagnose handle corruption problems.
    // We do not throw an exception because most code could not recover
    // from the problem.
}

備註

只有在 ReleaseHandle 屬性所 IsInvalid 定義的句柄有效時,方法才保證只能呼叫一次。 在您的衍生類別中實作 SafeHandle 這個方法,以執行釋放句柄所需的任何程序代碼。 因為的其中一個函式 SafeHandle 是保證資源外洩,所以 實 ReleaseHandle 作中的程式代碼絕對不能失敗。 在一般完成項執行之後,垃圾收集行程 ReleaseHandle 會呼叫同時收集垃圾的物件。 垃圾收集行程保證資源會叫用此方法,而且在進行中時不會中斷方法。

此外,如需簡單的清除 (,請在檔案句柄上呼叫 Windows API CloseHandle) 您可以檢查單一平臺調用呼叫的傳回值。 針對複雜的清除,您可能會有許多程式邏輯和許多方法呼叫,其中有些可能會失敗。 您必須確定程式邏輯具有每個案例的後援程序代碼。

如果ReleaseHandle因為任何原因而false傳回 ,它會在 .NET Framework 上執行時產生 releaseHandleFailed Managed 偵錯助理。 這有助於偵測嘗試釋放資源失敗的情況。

適用於

另請參閱