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 UnmanagedMutex("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.");
        }

        Console.ReadLine();
    }
}

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)]
    static extern SafeWaitHandle CreateMutex(IntPtr lpMutexAttributes, bool bInitialOwner,
    string lpName);

    // Use interop to call the ReleaseMutex function.
    // For more information about ReleaseMutex,
    // see the unmanaged MSDN reference library.
    [DllImport("kernel32.dll")]
    public static extern bool ReleaseMutex(SafeWaitHandle hMutex);

    private SafeWaitHandle handleValue = null;
    private IntPtr mutexAttrValue = IntPtr.Zero;
    private string nameValue = null;

    public UnmanagedMutex(string Name)
    {
        nameValue = Name;
    }

    public void Create()
    {
        if (nameValue == null && nameValue.Length == 0)
        {
            throw new ArgumentNullException("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 the handle is valid,
            // return it.
            if (!handleValue.IsInvalid)
            {
                return handleValue;
            }
            else
            {
                return null;
            }
        }
    }

    public string Name
    {
        get
        {
            return 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 . È un wrapper per i mutex Win32 e gli eventi di reimpostazione automatica e manuale.

Importante

Il tipo implementa l'interfaccia IDisposable. Dopo aver utilizzato il tipo, è necessario eliminarlo direttamente o indirettamente. Per eliminare direttamente il tipo, chiamare il metodo Dispose in un blocco try/catch. Per eliminarlo indirettamente, utilizzare un costrutto di linguaggio come ad esempio using in C# o Using in Visual Basic. Per altre informazioni, vedere la sezione "Uso di un oggetto che implementa IDisposable" nell'argomento relativo all'interfaccia IDisposable.

Costruttori

SafeWaitHandle()

Crea un oggetto SafeWaitHandle.

SafeWaitHandle(IntPtr, Boolean)

Inizializza una nuova istanza della classe SafeWaitHandle.

Campi

handle

Specifica l'handle di cui eseguire il wrapping.

(Ereditato da SafeHandle)

Proprietà

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

Close()

Contrassegna l'handle per il rilascio delle risorse.

(Ereditato da SafeHandle)
DangerousAddRef(Boolean)

Incrementa manualmente il numero di riferimenti nelle istanze di SafeHandle.

(Ereditato da SafeHandle)
DangerousGetHandle()

Restituisce il valore del campo handle.

(Ereditato da SafeHandle)
DangerousRelease()

Decrementa manualmente il numero di riferimenti in un'istanza di SafeHandle.

(Ereditato da SafeHandle)
Dispose()

Rilascia tutte le risorse usate dalla classe SafeHandle.

(Ereditato da SafeHandle)
Dispose(Boolean)

Rilascia le risorse non gestite usate dalla classe SafeHandle specificando se eseguire una normale operazione di eliminazione.

(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 l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
ReleaseHandle()

Quando ne viene eseguito l'override in una classe derivata, esegue il codice necessario per liberare l'handle.

(Ereditato da SafeHandle)
SetHandle(IntPtr)

Imposta l'handle sull'handle preesistente specificato.

(Ereditato da SafeHandle)
SetHandleAsInvalid()

Contrassegna un handle come non più usato.

(Ereditato da SafeHandle)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Si applica a

Vedi anche