SafeWaitHandle Classe

Definizione

Rappresenta una classe wrapper per un handle di attesa.

public ref class SafeWaitHandle sealed : System::Runtime::InteropServices::SafeHandle
public ref class SafeWaitHandle sealed : Microsoft::Win32::SafeHandles::SafeHandleZeroOrMinusOneIsInvalid
[System.Security.SecurityCritical]
public sealed class SafeWaitHandle : System.Runtime.InteropServices.SafeHandle
public sealed class SafeWaitHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
[System.Security.SecurityCritical]
public sealed class SafeWaitHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
[<System.Security.SecurityCritical>]
type SafeWaitHandle = class
    inherit SafeHandle
type SafeWaitHandle = class
    inherit SafeHandleZeroOrMinusOneIsInvalid
[<System.Security.SecurityCritical>]
type SafeWaitHandle = class
    inherit SafeHandleZeroOrMinusOneIsInvalid
Public NotInheritable Class SafeWaitHandle
Inherits SafeHandle
Public NotInheritable Class SafeWaitHandle
Inherits SafeHandleZeroOrMinusOneIsInvalid
Ereditarietà
SafeWaitHandle
Ereditarietà
Attributi

Esempio

Nell'esempio di codice seguente viene illustrato come usare l'interoperabilità per creare un mutex usando la SafeWaitHandle classe e la funzione non gestita CreateMutex .

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);
    }
}
Imports Microsoft.Win32.SafeHandles
Imports System.Runtime.InteropServices

Class SafeHandlesExample


    Shared Sub Main()
        Dim uMutex As New UnmanagedMutex("YourCompanyName_SafeHandlesExample_MUTEX")

        Try

            uMutex.Create()
            Console.WriteLine("Mutex created. Press Enter to release it.")
            Console.ReadLine()


        Catch e As Exception
            Console.WriteLine(e)
        Finally
            uMutex.Release()
            Console.WriteLine("Mutex Released.")
        End Try

        Console.ReadLine()

    End Sub
End Class


Class UnmanagedMutex



    ' Use interop to call the CreateMutex function.
    ' For more information about CreateMutex,
    ' see the unmanaged MSDN reference library.
    <DllImport("kernel32.dll", CharSet:=CharSet.Unicode)> _
    Shared Function CreateMutex(ByVal lpMutexAttributes As IntPtr, ByVal bInitialOwner As Boolean, ByVal lpName As String) As SafeWaitHandle

    End Function



    ' Use interop to call the ReleaseMutex function.
    ' For more information about ReleaseMutex,
    ' see the unmanaged MSDN reference library.
    <DllImport("kernel32.dll")> _
    Public Shared Function ReleaseMutex(ByVal hMutex As SafeWaitHandle) As Boolean

    End Function



    Private handleValue As SafeWaitHandle = Nothing
    Private mutexAttrValue As IntPtr = IntPtr.Zero
    Private nameValue As String = Nothing


    Public Sub New(ByVal Name As String)
        nameValue = Name

    End Sub



    Public Sub Create()
        If nameValue Is Nothing AndAlso nameValue.Length = 0 Then
            Throw New ArgumentNullException("nameValue")
        End If

        handleValue = CreateMutex(mutexAttrValue, True, nameValue)

        ' If the handle is invalid,
        ' get the last Win32 error 
        ' and throw a Win32Exception.
        If handleValue.IsInvalid Then
            Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error())
        End If

    End Sub


    Public ReadOnly Property Handle() As SafeWaitHandle
        Get
            ' If the handle is valid,
            ' return it.
            If Not handleValue.IsInvalid Then
                Return handleValue
            Else
                Return Nothing
            End If
        End Get
    End Property


    Public ReadOnly Property Name() As String
        Get
            Return nameValue
        End Get
    End Property



    Public Sub Release()
        ReleaseMutex(handleValue)

    End Sub
End Class

Commenti

La SafeWaitHandle classe viene utilizzata dalla System.Threading.WaitHandle classe . Si tratta di un wrapper per mutex Win32 ed eventi di reimpostazione automatica e manuale.

Importante

Questo tipo implementa l'interfaccia IDisposable . Al termine dell'uso del tipo, è necessario eliminarlo direttamente o indirettamente. Per eliminare direttamente il tipo, chiamare il Dispose relativo metodo in un try/catch blocco. Per eliminarlo indirettamente, usare un costrutto del linguaggio, ad using esempio (in C#) o Using (in Visual Basic).

Costruttori

Nome Descrizione
SafeWaitHandle()

Crea un SafeWaitHandle.

SafeWaitHandle(IntPtr, Boolean)

Inizializza una nuova istanza della classe SafeWaitHandle.

Campi

Nome Descrizione
handle

Specifica l'handle di cui eseguire il wrapping.

(Ereditato da SafeHandle)

Proprietà

Nome Descrizione
IsClosed

Ottiene un valore che indica se l'handle è chiuso.

(Ereditato da SafeHandle)
IsInvalid

Ottiene un valore che indica se l'handle non è valido.

IsInvalid

Ottiene un valore che indica se l'handle non è valido.

(Ereditato da SafeHandleZeroOrMinusOneIsInvalid)

Metodi

Nome Descrizione
Close()

Contrassegna l'handle per il rilascio e la liberazione delle risorse.

(Ereditato da SafeHandle)
DangerousAddRef(Boolean)

Incrementa manualmente il contatore di riferimento nelle SafeHandle istanze di .

(Ereditato da SafeHandle)
DangerousGetHandle()

Restituisce il valore del handle campo.

(Ereditato da SafeHandle)
DangerousRelease()

Decrementa manualmente il contatore di riferimento in un'istanza SafeHandle di .

(Ereditato da SafeHandle)
Dispose()

Rilascia tutte le risorse usate dalla SafeHandle classe .

(Ereditato da SafeHandle)
Dispose(Boolean)

Rilascia le risorse non gestite usate dalla SafeHandle classe specificando se eseguire un'operazione dispose normale.

(Ereditato da SafeHandle)
Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
ReleaseHandle()

Quando sottoposto a override in una classe derivata, esegue il codice necessario per liberare l'handle.

(Ereditato da SafeHandle)
SetHandle(IntPtr)

Imposta l'handle sull'handle esistente specificato.

(Ereditato da SafeHandle)
SetHandleAsInvalid()

Contrassegna un handle come non più utilizzato.

(Ereditato da SafeHandle)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Si applica a

Vedi anche