Redigera

Dela via


SafeHandle.ReleaseHandle Method

Definition

When overridden in a derived class, executes the code required to free the handle.

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

Returns

true if the handle is released successfully; otherwise, in the event of a catastrophic failure, false. In this case, it generates a releaseHandleFailed Managed Debugging Assistant.

Examples

The following code example releases the handle and is part of a larger example provided for the SafeHandle class.

[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.
}

Remarks

The ReleaseHandle method is guaranteed to be called only once and only if the handle is valid as defined by the IsInvalid property. Implement this method in your SafeHandle derived classes to execute any code that is required to free the handle. Because one of the functions of SafeHandle is to guarantee prevention of resource leaks, the code in your implementation of ReleaseHandle must never fail. The garbage collector calls ReleaseHandle after normal finalizers have been run for objects that were garbage collected at the same time. The garbage collector guarantees the resources to invoke this method and that the method will not be interrupted while it is in progress.

Additionally, for simple cleanup (for example, calling the Windows API CloseHandle on a file handle) you can check the return value for the single platform invoke call. For complex cleanup, you may have a lot of program logic and many method calls, some of which might fail. You must ensure that your program logic has fallback code for each of those cases.

If ReleaseHandle returns false for any reason, it generates a releaseHandleFailed Managed Debugging Assistant when running on .NET Framework. This helps you detect cases where your attempt to release resources fails.

Applies to

See also