我有许多读取xml文件的服务。为了确保没有冲突,我使用互斥锁。无论出于何种原因,如果我的所有服务都由同一个用户运行,则没有问题。但是,如果有不同的用户运行这些服务,即使一个服务释放了互斥锁,另一个服务在调用enter route mutex时会出现以下异常“Unhandled Exception:System.TypeInitializationException:'createMutex.Program'的类型初始值设定项引发了exception。---> System.UnauthorizedAccessException:拒绝访问路径'RETEST_MUTEX'。“
public static readonly String ROUTE_MUTEX_STRING = "RETEST_MUTEX";
private static Mutex _routeMutex = new Mutex(false, ROUTE_MUTEX_STRING);
/// <summary>
/// Thin wrapper around the static routeMutex WaitOne method
/// Always call ExitRouteMutex when done in protected area
/// </summary>
/// <param name="millis_timeout"></param>
/// <returns>true if signaled, like WaitOne</returns>
public static bool EnterRouteMutex(int millis_timeout)
{
try
{
return _routeMutex.WaitOne(millis_timeout, false);
}
catch (AbandonedMutexException ame)
{
// swallow this exception - don't want to depend on other apps being healthy - like pre .NET 2.0 behavior
// data integrity will be checked
return _routeMutex.WaitOne(millis_timeout, false);
}
}
public static void ExitRouteMutex()
{
try
{
_routeMutex.ReleaseMutex();
}
catch (ApplicationException)
{
// swallow, reduce complexity to client
}
}
static void Main(string[] args)
{
Console.WriteLine("Start");
bool get = EnterRouteMutex(1000);
System.Console.WriteLine("Mutex created Press enter " + get.ToString());
Console.ReadLine();
ExitRouteMutex();
Console.WriteLine("Mutex Release");
System.Console.WriteLine("Press enter");
Console.ReadLine();
}
答案 0 :(得分:3)
以下是执行跨进程互斥锁的示例。
http://msdn.microsoft.com/en-us/library/c41ybyt3.aspx
它处理Mutex.OpenExisting的使用,并演示了cdhowie提到的安全方面。