How do I allow only 1 named Semaphore to be create

2019-08-30 01:44发布

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条回答
Fickle 薄情
2楼-- · 2019-08-30 02:19

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");
查看更多
登录 后发表回答