SafeWaitHandle Class

Definition

Represents a wrapper class for a wait handle.

C#
[System.Security.SecurityCritical]
public sealed class SafeWaitHandle : System.Runtime.InteropServices.SafeHandle
C#
public sealed class SafeWaitHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
C#
[System.Security.SecurityCritical]
public sealed class SafeWaitHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
Inheritance
SafeWaitHandle
Inheritance
Attributes

Examples

The following code example demonstrates how to use interop to create a mutex using the SafeWaitHandle class and the unmanaged CreateMutex function.

C#
using System;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;

class SafeHandlesExample
{
    static void Main()
    {
        UnmanagedMutex uMutex = new("YourCompanyName_SafeHandlesExample_MUTEX");

        try
        {
            uMutex.Create();
            Console.WriteLine("Mutex created. Press Enter to release it.");
            Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
            uMutex.Release();
            Console.WriteLine("Mutex released.");
        }
    }
}

partial class UnmanagedMutex(string Name)
{
    // Use interop to call the CreateMutex function.
    [LibraryImport("kernel32.dll", EntryPoint = "CreateMutexW", StringMarshalling = StringMarshalling.Utf16)]
    private static partial SafeWaitHandle CreateMutex(
        IntPtr lpMutexAttributes,
        [MarshalAs(UnmanagedType.Bool)] bool bInitialOwner,
        string lpName
        );

    // Use interop to call the ReleaseMutex function.
    // For more information about ReleaseMutex,
    // see the unmanaged MSDN reference library.
    [LibraryImport("kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static partial bool ReleaseMutex(SafeWaitHandle hMutex);

    private SafeWaitHandle _handleValue = null;
    private readonly IntPtr _mutexAttrValue = IntPtr.Zero;
    private string nameValue = Name;

    public void Create()
    {
        ArgumentException.ThrowIfNullOrEmpty(nameValue);

        _handleValue = CreateMutex(_mutexAttrValue,
                                        true, nameValue);

        // If the handle is invalid,
        // get the last Win32 error
        // and throw a Win32Exception.
        if (_handleValue.IsInvalid)
        {
            Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
        }
    }

    public SafeWaitHandle Handle
    {
        get
        {
            if (!_handleValue.IsInvalid)
            {
                return _handleValue;
            }
            else
            {
                return null;
            }
        }
    }

    public string Name => nameValue;

    public void Release()
    {
        ReleaseMutex(_handleValue);
    }
}

Remarks

The SafeWaitHandle class is used by the System.Threading.WaitHandle class. It is a wrapper for Win32 mutexes and auto and manual reset events.

Important

This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic).

Constructors

SafeWaitHandle()

Creates a SafeWaitHandle.

SafeWaitHandle(IntPtr, Boolean)

Initializes a new instance of the SafeWaitHandle class.

Fields

handle

Specifies the handle to be wrapped.

(Inherited from SafeHandle)

Properties

IsClosed

Gets a value indicating whether the handle is closed.

(Inherited from SafeHandle)
IsInvalid

Gets a value that indicates whether the handle is invalid.

IsInvalid

Gets a value that indicates whether the handle is invalid.

(Inherited from SafeHandleZeroOrMinusOneIsInvalid)

Methods

Close()

Marks the handle for releasing and freeing resources.

(Inherited from SafeHandle)
DangerousAddRef(Boolean)

Manually increments the reference counter on SafeHandle instances.

(Inherited from SafeHandle)
DangerousGetHandle()

Returns the value of the handle field.

(Inherited from SafeHandle)
DangerousRelease()

Manually decrements the reference counter on a SafeHandle instance.

(Inherited from SafeHandle)
Dispose()

Releases all resources used by the SafeHandle class.

(Inherited from SafeHandle)
Dispose(Boolean)

Releases the unmanaged resources used by the SafeHandle class specifying whether to perform a normal dispose operation.

(Inherited from SafeHandle)
Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ReleaseHandle()

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

(Inherited from SafeHandle)
SetHandle(IntPtr)

Sets the handle to the specified pre-existing handle.

(Inherited from SafeHandle)
SetHandleAsInvalid()

Marks a handle as no longer used.

(Inherited from SafeHandle)
ToString()

Returns a string that represents the current object.

(Inherited from Object)

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

See also