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를 사용하여 클래스 및 관리 CreateMutex 되지 않는 함수를 SafeWaitHandle 사용하여 뮤텍스를 만드는 방법을 보여 줍니다.

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

설명

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

중요

이 형식이 구현 하는 IDisposable 인터페이스입니다. 형식을 사용 하 여 마쳤으면 직접 또는 간접적으로의 삭제 해야 있습니다. 직접 형식의 dispose 호출 해당 Dispose 의 메서드를 try/catch 블록입니다. 삭제 하지 직접, 언어 구문 같은 사용 using (C#에서) 또는 Using (Visual Basic에서는). 자세한 내용은 "를 사용 하는 개체는 구현 IDisposable" 섹션을 참조 하세요.를 IDisposable 인터페이스 항목입니다.

생성자

SafeWaitHandle()

SafeWaitHandle을 만듭니다.

SafeWaitHandle(IntPtr, Boolean)

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

필드

handle

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

(다음에서 상속됨 SafeHandle)

속성

IsClosed

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

(다음에서 상속됨 SafeHandle)
IsInvalid

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

IsInvalid

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

(다음에서 상속됨 SafeHandleZeroOrMinusOneIsInvalid)

메서드

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)

적용 대상

추가 정보