Paul Allan said:
Carl.
Thanks for getting back to me with your valuable insight.
Below is my singleton class where I tried to use the
System.Threading.Semaphore class.
I just Googled the System.Threading.Mutex class, and I think your right.
How do I use a named Mutex in my singleton class?
Just replace System.Threading.Semaphore with System.Threading.Mutex and
replace the call to .Release() with a call to .ReleaseMutex(). You need to
call one of the constructors that takes a name in order to create a named
mutex. It you don't create a named mutex, you'd need to communicate the
handle to other processes in order to get cross-process synchronization.
Do I need a singleton class or will a named mutex work across many
instances of my class?
You don't really need a singleton, but it's not a bad design. You can
actually create as many System.Threading.Mutex objects as you wish and as
long as they all refer to the same named mutex, they all share a single
synchronization context across all threads and processes.
Why do you believe that you need to synchronize access across multiple
processes? I'm guessing that you're probably writing to some shared state
(e.g. a log file). If that's the case, you also need to make sure to flush
writes to the shared resource (e.g. by calling System.IO.Stream.Flush())
while you own the mutex to make sure that all output is actually written
before leaving the synchronized block.
There's usually a better solution than global synchronization though - it's
quite expensive. So if you can provide some details of the kind of
operation you're trying to protect, someone may well be able to come up with
a better solution.
-cd