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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
petr_hlucinAuthor Commented:
Tried that with the same result - the exception is raised on mutex creation.
0
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Shahan AyyubSenior Software EngineerCommented:
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 EngineerCommented:
Further a 'WaitHandleCannotBeOpenedException' must be handled, because if 'Openexisting'  fails to do its task a 'WaitHandleCannotBeOpenedException' raises instead of null.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.