Mutex System.UnauthorizedAccessException

Hello Experts,

In Windows service which we develop in C# (.NET 2.0) we have to use Mutexes. Very occasionally (approx. 1 attempt of 100k attempts) the following exception is raised:

System.UnauthorizedAccessException: Access to the path 'Global\{3B80AED0-B58A-48c3-BC84-D2892FEB8E39}' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.Threading.Mutex.<>c__DisplayClass3.<.ctor>b__0(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew, MutexSecurity mutexSecurity)
   at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name)
   at MailArchiveCommon.Utils.Fulltext.GetHits(String query, Object[] args) in File.cs:line 48

On File.cs:48 the following block starts (it is exactly the "using" line):
            using (var mutex = new Mutex(false, MutexID))
            {
                mutex.WaitOne();
                try
                {
                   // Do some stuff...
                }
                finally
                {
                    mutex.ReleaseMutex();
                }
            }

Currently it runs on Win2k3 machine.

Does anybody have any idea what it could be caused by and how to get rid of this exception?
LVL 4
petr_hlucinAsked:
Who is Participating?
 
mastooCommented:
or to attach the sample code from that link...
try  
      {  
        smsMutex = Mutex.OpenExisting(MutexName);  
      }  
        //mutex doesn't exist, create it  
      catch (WaitHandleCannotBeOpenedException)  
      {  
        SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);   
  
        MutexSecurity mSec = new MutexSecurity();  
  
        MutexAccessRule rule = new MutexAccessRule(sid, MutexRights.FullControl,  
            AccessControlType.Allow);  
  
        mSec.AddAccessRule(rule);  
  
        bool mutexIsNew = false;  
  
        smsMutex = new Mutex(false, MutexName, out mutexIsNew, mSec);  
      }

Open in new window

0
 
petr_hlucinAuthor Commented:
I've figured out that this exception occurs when this mutex is accessed from 2 processes at once. Does this mean that I can't use named mutex for securing a resource which may be accessed by 2 processes? Which synchronization primitive should I use then?
0
 
Chuck YetterCommented:
I would check to see if the mutex already exists before tyring to create it.  Check out the overloaded Mutex constructors documentation from Visual Studio (code snippet).
        // Set this variable to false if you do not want to request 
        // initial ownership of the named mutex.
        bool requestInitialOwnership = true;
        bool mutexWasCreated;

        // Request initial ownership of the named mutex by passing
        // true for the first parameter. Only one system object named 
        // "MyMutex" can exist; the local Mutex object represents 
        // this system object. If "MyMutex" is created by this call,
        // then mutexWasCreated contains true; otherwise, it contains
        // false.
        Mutex m = new Mutex(requestInitialOwnership, 
                            "MyMutex", 
                            out mutexWasCreated);

        // This thread owns the mutex only if it both requested 
        // initial ownership and created the named mutex. Otherwise,
        // it can request the named mutex by calling WaitOne.
        if (!(requestInitialOwnership && mutexWasCreated))
        {
            Console.WriteLine("Waiting for the named mutex.");
            m.WaitOne();
        }

        // Once the process has gained control of the named mutex,
        // hold onto it until the user presses ENTER.
        Console.WriteLine("This process owns the named mutex. " +
            "Press ENTER to release the mutex and exit.");
        Console.ReadLine();

        // Call ReleaseMutex to allow other threads to gain control
        // of the named mutex. If you keep a reference to the local
        // Mutex, you can call WaitOne to request control of the 
        // named mutex.
        m.ReleaseMutex();

Open in new window

0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
petr_hlucinAuthor Commented:
Tried that with the same result - the exception is raised on mutex creation.
0
 
petr_hlucinAuthor Commented:
This problem occurs only sometimes when 2 processes try to access the same resource. When I run any of the 2 processes individually this error never happens. It's therefore not an access rights issue.
0
 
mastooCommented:
Could you explain your conclusion?  If the mutex gets created with restricted access, that is exactly when you would have the exception (when two threads try to access the same mutex at the same time).
0
 
petr_hlucinAuthor Commented:
Yes, maybe you have a point. It could be an access control issue. I will investigate further and let you know ...
0
 
petr_hlucinAuthor Commented:
Do you know how to grant rights to this mutex for all users? I don't know which user will the 2 processes run under (usually the 2 instances run under different accounts).
0
 
mastooCommented:
I haven't done much with mutexes across processes but this person seems to have solved your exact problem:

http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/5d41769b-2a0d-4129-906e-5dd67427fe2a
0
 
Shahan AyyubSenior Software Engineer - iOSCommented:
mastoo provided you the correct guidance. I found this in a book that the MUTEX class can locks data across AppDomain and process boundaries. so, whenever two object were trying get access, MUTEX appears to be locked.
0
 
Shahan AyyubSenior Software Engineer - iOSCommented:
Further a 'WaitHandleCannotBeOpenedException' must be handled, because if 'Openexisting'  fails to do its task a 'WaitHandleCannotBeOpenedException' raises instead of null.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.