Lamont said:
Actually, yeah, that's what I was using it for... but consider this:
I'm attempting to own the Mutex in the context of a fairly large try{}
block. The finally{} handler performs a ReleaseMutex() and Close()... but
ReleaseMutex() should only be called if the Mutex is actually owned by the
executing process. I need to know whether the Mutex is owned (by my
currently executing process) before attempting to release it.
A mutex is owned by a thread, not a process. Using a named mutex you
can accomplish inter-process synchronization, but it's still a specific
thread within the process that owns the mutex.
This may or may not be relevant in your own case (e.g. it wouldn't
matter for a single-threaded application), but it's worth pointing out IMHO.
I could always set and check my own internal bool variable ('isMutexOwned'),
and that works just fine, but it just struck me as odd that the Mutex didn't
provide an IsOwned property -- similar to the IsReaderLockHeld property of
the ReaderWriter lock.
For what it's worth, the property you seem to want is significantly
different from the property that most (if not all) of us assumed you
wanted. That is, you seem to be asking for a way to know if the
executing thread is actually the one holding the mutex. This is a lot
different from simply wanting to know if the mutex is being held by
_any_ thread (in-process or otherwise).
Now, all that said...it seems to me that if you don't want to keep a
local variable to track whether you've successfully acquired the mutex
or not, you should simply acquire the mutex _before_ the
try/catch/finally block of code. IMHO, code protected by a mutex (or
other synchronization object, for that matter) should generally look
like this:
if (/* successfully acquire object */)
{
/* Do some work */
/* release acquired object */
}
In other words, the object "protects" a section of code, and at the very
end of that section, you release the object. So, instead of this:
bool fHaveObject = false;
try
{
if (/* successfully acquire object */
{
fHaveObject = true;
/* Do some work */
}
}
finally
{
if (fHaveObject)
{
/* release acquired object */
}
}
You should have something like this:
if (/* successfully acquire object */)
{
try
{
/* Do some work */
}
finally
{
/* release acquired object */
}
}
You may have to nest try/finally blocks to use that pattern (depending
on what else the code is doing), but IMHO if you have a block of code so
large that's a problem, you probably are dealing with some code that
ought to be broken into multiple methods anyway.
If that specific pattern doesn't work in your case, and you would like
something different than what you actually have, you might consider
posting the block of code that's giving you trouble. I'll bet someone
will have an idea of a different way to do it.
Pete