David Thielen
David Thielen

Reputation: 32966

How do I allow only 1 named Semaphore to be created on a server?

I would like to create a semaphore in my app, where the creation will fail (with a clear exception), if another instance of the app is running and has already created the semaphore. So only one per server.

I'd like the limit of only one to hold across the system, not just the CLR. But I do not want it to hold across multiple servers (or VMs). i.e. I want the app able to run on 2 distinct servers.

Is this possible? If so, how?

thanks - dave

Upvotes: 0

Views: 165

Answers (1)

I4V
I4V

Reputation: 35363

You can use System.Threading.Mutex for this.

Named system mutexes are visible throughout the operating system, and can be used to synchronize the activities of processes.

bool b = true;
Mutex mutex = new Mutex(true, "MyMutex", out b);
if (!b) throw new InvalidOperationException("Another instance is running");

Upvotes: 1

Related Questions