alexandrul
alexandrul

Reputation: 13266

C# mutex - error calling from ASP.NET and console application

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

Upvotes: 7

Views: 9754

Answers (2)

Vladislav
Vladislav

Reputation: 2005

Here the sample from How to determine if a previous instance of my application is running? (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);

Upvotes: 7

littlegeek
littlegeek

Reputation:

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...=>

Upvotes: 11

Related Questions