tags:

views:

2375

answers:

2

I am using a global named mutex for file access synchronization between an ASP.NET application and a console application.

While running the ASP.NET application, the console application fails to acquire mutex - as expected. While running the console application, the ASP.NET application throws UnauthorizedAccessException: Access to the path 'Global\TheNameOfTheMutex' is denied.

I will try to catch the exception and treat it like it failed to acquire the mutex, but I want to know why is it behaving like this? The ASP.NET application runs as expected if it is accessed from two different browsers and the console applications also runs as expected when running multiple instances.

Update: on Windows XP the exception is also thrown when the ASP.NET application is running and I try to start the console application.

The code used for synchronization is in a common assembly:

using (Mutex m = new Mutex(false, "Global\\TheNameOfTheMutex")) // exception thrown
{
  try
  {
    lock = m.WaitOne(0, false);
  }
  catch (AbandonedMutexException)
  {
    // ...
  }

  if(lock)
  {
    // ...

    m.ReleaseMutex();
  }
}

Environment: Windows Server 2008, IIS 7, ASP.NET 2.0

+6  A: 

do you have the right user set up to access to the resources? using

MutexSecurity and MutexAccessRule ?

try looking at this on MSDN http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.mutexsecurity.aspx

and http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.mutexaccessrule.aspx

p.s. I am awaiting a Jon Skeet answer to show my ignorance in the matter...=>

My "answer" is just to +1 yours, as it looks exactly right to me :)
Jon Skeet
the high point of my day - Jon Skeet talked to me => And agreed happy day
+1  A: 

Here the sample from http://stackoverflow.com/questions/778817/how-to-determine-if-a-previous-instance-of-my-application-is-running-c (see the romkyns' answer)

    var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
    var mutexsecurity = new MutexSecurity();
    mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow));
    mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny));
    mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny));
    _mutex = new Mutex(false, "Global\\YourAppName-{add-your-random-chars}", out created, mutexsecurity);
Vladislav