SafeWaitHandle Class
Assembly: mscorlib (in mscorlib.dll)
The SafeWaitHandle class is used by the System.Threading.WaitHandle class. It is a wrapper for Win32 mutexes and auto and manual reset events.
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")] 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.GetLastWin32Error()); } } 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); } }
System.Runtime.ConstrainedExecution.CriticalFinalizerObject
System.Runtime.InteropServices.SafeHandle
Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
Microsoft.Win32.SafeHandles.SafeWaitHandle
Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.