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

天涯浪子 提交于 2019-12-12 00:26:55

问题


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


来源:https://stackoverflow.com/questions/16990181/how-do-i-allow-only-1-named-semaphore-to-be-created-on-a-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!