SafeWaitHandle 클래스

정의

대기 핸들에 대한 래퍼 클래스를 나타냅니다.

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
상속
SafeWaitHandle
상속
특성

예제

다음 코드 예제에서는 interop를 사용하여 클래스 및 관리 SafeWaitHandle 되지 않는 함수를 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

설명

클래스는 SafeWaitHandle 클래스에서 System.Threading.WaitHandle 사용됩니다. Win32 뮤텍스 및 자동 및 수동 재설정 이벤트에 대한 래퍼입니다.

Important

이 형식은 IDisposable 인터페이스를 구현합니다. 형식 사용을 마쳤으면 직접 또는 간접적으로 삭제해야 합니다. 형식을 직접 삭제하려면 Disposetry/ 블록에서 해당 catch 메서드를 호출합니다. 간접적으로 삭제하려면 using(C#) 또는 Using(Visual Basic)와 같은 언어 구문을 사용합니다.

생성자

Name Description
SafeWaitHandle()

SafeWaitHandle 항목을 만듭니다.

SafeWaitHandle(IntPtr, Boolean)

SafeWaitHandle 클래스의 새 인스턴스를 초기화합니다.

필드

Name Description
handle

래핑할 핸들을 지정합니다.

(다음에서 상속됨 SafeHandle)

속성

Name Description
IsClosed

핸들이 닫혀 있는지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 SafeHandle)
IsInvalid

핸들이 잘못된지 여부를 나타내는 값을 가져옵니다.

IsInvalid

핸들이 잘못된지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 SafeHandleZeroOrMinusOneIsInvalid)

메서드

Name Description
Close()

리소스를 해제하고 해제하기 위한 핸들을 표시합니다.

(다음에서 상속됨 SafeHandle)
DangerousAddRef(Boolean)

인스턴스에서 참조 카운터 SafeHandle 를 수동으로 증분합니다.

(다음에서 상속됨 SafeHandle)
DangerousGetHandle()

필드의 값을 반환합니다 handle .

(다음에서 상속됨 SafeHandle)
DangerousRelease()

인스턴스에서 참조 카운터 SafeHandle 를 수동으로 감소합니다.

(다음에서 상속됨 SafeHandle)
Dispose()

클래스에서 사용하는 모든 리소스를 해제합니다 SafeHandle .

(다음에서 상속됨 SafeHandle)
Dispose(Boolean)

일반 삭제 작업을 수행할지 여부를 지정하는 클래스에서 SafeHandle 사용하는 관리되지 않는 리소스를 해제합니다.

(다음에서 상속됨 SafeHandle)
Equals(Object)

지정된 개체가 현재 개체와 같은지 여부를 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 사용됩니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ReleaseHandle()

파생 클래스에서 재정의된 경우 핸들을 해제하는 데 필요한 코드를 실행합니다.

(다음에서 상속됨 SafeHandle)
SetHandle(IntPtr)

핸들을 지정된 기존 핸들로 설정합니다.

(다음에서 상속됨 SafeHandle)
SetHandleAsInvalid()

핸들을 더 이상 사용되지 않는 것으로 표시합니다.

(다음에서 상속됨 SafeHandle)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

적용 대상

추가 정보