本文整理匯總了C#中Microsoft.Win32.SafeHandles.SafeWaitHandle類的典型用法代碼示例。如果您正苦於以下問題:C# SafeWaitHandle類的具體用法?C# SafeWaitHandle怎麽用?C# SafeWaitHandle使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
SafeWaitHandle類屬於Microsoft.Win32.SafeHandles命名空間,在下文中一共展示了SafeWaitHandle類的1個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: Main
//引入命名空間
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);
}
}