Mutex won't release after exception.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I want a (global) mutex which prevents a section of my code from being run by more than one process (or user) at a time. I have something that works, EXCEPT when there is an exception of some kind. It is possible for the user to generate an error and be able to "fix" the thing that caused the error (perhaps by changing some parameter) and then want to run the operation again from the same process. But if there's been an error, then he's out of luck and has to restart the process (which, in some cases is a bit arduous.

So, to summarize. It works perfectly as long as there is no error. When there is an error, the process has to be restarted. I need a way to guard my "DoStuff()" code so that only one thread/process/user is ever running it at any time and when it fails, the process does not have to be shut down to release the mutex

My code looks like the following
if ( WantToDoStuff (...)

bool got_ownership
Mutex mt = new Mutex(true, "Company.Division.Project.Subproject.Component", out got_ownership)
if ( got_ownership

tr

DoStuff ( ... )
GC.Collect()

catch ( Exception e

error_message = e.Message + e.StackTrace

GC.Collect()
mt.ReleaseMutex()

els

error_message = "Didn't get mutex."


GC.Collect()
 
Lowell said:
So, to summarize. It works perfectly as long as there is no error.
When there is an error, the process has to be restarted. I need a way
to guard my "DoStuff()" code so that only one thread/process/user is
ever running it at any time and when it fails, the process does not
have to be shut down to release the mutex.

You have misunderstood the purpose of the third parameter to the Mutex
constructor. It doesn't say whether or not you've got ownership, it
says whether or not the mutex had to be constructed.

Instead of the code you've got, you should create the mutex without
bothering to try to gain ownership, and then call WaitOne on it.
 
Bingo

Thanks

Lowel

----- Jon Skeet [C# MVP] wrote: ----

Lowell said:
So, to summarize. It works perfectly as long as there is no error
When there is an error, the process has to be restarted. I need a wa
to guard my "DoStuff()" code so that only one thread/process/user i
ever running it at any time and when it fails, the process does no
have to be shut down to release the mutex

You have misunderstood the purpose of the third parameter to the Mutex
constructor. It doesn't say whether or not you've got ownership, it
says whether or not the mutex had to be constructed

Instead of the code you've got, you should create the mutex without
bothering to try to gain ownership, and then call WaitOne on it
 
Back
Top