SafeWaitHandle 類別

定義

代表等候控制代碼的包裝函式類別。Represents a wrapper class for a wait handle.

public ref class SafeWaitHandle sealed : Microsoft::Win32::SafeHandles::SafeHandleZeroOrMinusOneIsInvalid
[System.Security.SecurityCritical]
public sealed class SafeWaitHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
type SafeWaitHandle = class
    inherit SafeHandleZeroOrMinusOneIsInvalid
Public NotInheritable Class SafeWaitHandle
Inherits SafeHandleZeroOrMinusOneIsInvalid
繼承
屬性

範例

下列程式碼範例示範如何使用 interop 來建立使用SafeWaitHandle類別和非受控CreateMutex函式的 mutex。The following code example demonstrates how to use interop to create a mutex using the SafeWaitHandle class and the unmanaged CreateMutex function.

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由類別使用。The SafeWaitHandle class is used by the System.Threading.WaitHandle class. 這是 Win32 mutex 和自動和手動重設事件的包裝函式。It is a wrapper for Win32 mutexes and auto and manual reset events.

重要

此型別代表 IDisposable 介面。This type implements the IDisposable interface. 當您完成使用型別時,您應該直接或間接處置它。When you have finished using the type, you should dispose of it either directly or indirectly. 若要直接處置型別,請呼叫其 try/catch 區塊中的 Dispose 方法。To dispose of the type directly, call its Dispose method in a try/catch block. 若要間接處置它,請使用語言建構函式,例如 using (在 C# 中) 或 Using (在 Visual Basic 中)。To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 如需詳細資訊,請參閱 IDisposable 介面文章中的<使用實作 IDisposable 的物件>一節。For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

建構函式

SafeWaitHandle(IntPtr, Boolean)

初始化 SafeWaitHandle 類別的新執行個體。Initializes a new instance of the SafeWaitHandle class.

欄位

handle

指定要包裝的控制代碼。Specifies the handle to be wrapped.

(繼承來源 SafeHandle)

屬性

IsClosed

取得值,指出控制代碼是否已關閉。Gets a value indicating whether the handle is closed.

(繼承來源 SafeHandle)
IsInvalid

取得值,這個值表示控制代碼是否無效。Gets a value that indicates whether the handle is invalid.

方法

Close()

標記要釋出和釋放資源的控制代碼。Marks the handle for releasing and freeing resources.

(繼承來源 SafeHandle)
DangerousAddRef(Boolean)

手動遞增 SafeHandle 執行個體上的參考計數器。Manually increments the reference counter on SafeHandle instances.

(繼承來源 SafeHandle)
DangerousGetHandle()

傳回 handle 欄位的值。Returns the value of the handle field.

(繼承來源 SafeHandle)
DangerousRelease()

手動遞減 SafeHandle 執行個體上的參考計數器。Manually decrements the reference counter on a SafeHandle instance.

(繼承來源 SafeHandle)
Dispose()

釋放 SafeHandle 類別所使用的所有資源。Releases all resources used by the SafeHandle class.

(繼承來源 SafeHandle)
Dispose(Boolean)

釋放 SafeHandle 類別所使用的 Unmanaged 資源,指定是否要執行一般處置 (Dispose) 作業。Releases the unmanaged resources used by the SafeHandle class specifying whether to perform a normal dispose operation.

(繼承來源 SafeHandle)
Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
ReleaseHandle()

在衍生類別中覆寫時,執行釋放控制代碼所需的程式碼。When overridden in a derived class, executes the code required to free the handle.

(繼承來源 SafeHandle)
SetHandle(IntPtr)

將控制代碼設定為指定的既有控制代碼。Sets the handle to the specified pre-existing handle.

(繼承來源 SafeHandle)
SetHandleAsInvalid()

將控制代碼標記為不再使用。Marks a handle as no longer used.

(繼承來源 SafeHandle)
ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

安全性

SecurityCriticalAttribute
需要完全信任立即呼叫者。requires full trust for the immediate caller. 部分信任或透明的程式碼無法使用這個成員。This member cannot be used by partially trusted or transparent code.

適用於

另請參閱