Idioma

SafeWaitHandle Classe

Definição

Representa uma classe wrapper para um identificador de espera.

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
Herança
SafeWaitHandle
Herança
Atributos

Exemplos

O exemplo de código a seguir demonstra como usar a interoperabilidade para criar um mutex usando a SafeWaitHandle classe e a função não gerenciada 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

Comentários

A SafeWaitHandle classe é usada pela System.Threading.WaitHandle classe. É um wrapper para mutexes Win32 e eventos de redefinição automática e manual.

Importante

Esse tipo implementa a IDisposable interface. Quando terminar de usar esse tipo ou objeto, você deverá descartá-lo de forma direta ou indireta. Para descartar o tipo diretamente, chame o método Dispose dele em um bloco try/catch. Para descartá-lo indiretamente, use um constructo de linguagem como using (em C#) ou Using (no Visual Basic).

Construtores

Nome Description
SafeWaitHandle()

Cria um SafeWaitHandle.

SafeWaitHandle(IntPtr, Boolean)

Inicializa uma nova instância da classe SafeWaitHandle.

Campos

Nome Description
handle

Especifica o identificador a ser encapsulado.

(Herdado de SafeHandle)

Propriedades

Nome Description
IsClosed

Obtém um valor que indica se o identificador está fechado.

(Herdado de SafeHandle)
IsInvalid

Obtém um valor que indica se o identificador é inválido.

IsInvalid

Obtém um valor que indica se o identificador é inválido.

(Herdado de SafeHandleZeroOrMinusOneIsInvalid)

Métodos

Nome Description
Close()

Marca o identificador para liberar e liberar recursos.

(Herdado de SafeHandle)
DangerousAddRef(Boolean)

Incrementa manualmente o contador de referência em SafeHandle instâncias.

(Herdado de SafeHandle)
DangerousGetHandle()

Retorna o valor do handle campo.

(Herdado de SafeHandle)
DangerousRelease()

Diminui manualmente o contador de referência em uma SafeHandle instância.

(Herdado de SafeHandle)
Dispose()

Libera todos os recursos usados pela SafeHandle classe.

(Herdado de SafeHandle)
Dispose(Boolean)

Libera os recursos não gerenciados usados pela SafeHandle classe especificando se uma operação de descarte normal deve ser executada.

(Herdado de SafeHandle)
Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Objectatual.

(Herdado de Object)
ReleaseHandle()

Quando substituído em uma classe derivada, executa o código necessário para liberar o identificador.

(Herdado de SafeHandle)
SetHandle(IntPtr)

Define o identificador para o identificador pré-existente especificado.

(Herdado de SafeHandle)
SetHandleAsInvalid()

Marca um identificador como não mais usado.

(Herdado de SafeHandle)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Aplica-se a

Confira também