How do I allow only 1 named Semaphore to be create

2019-08-30 01:40发布

问题:

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

回答1:

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");