.NET - 限制执行单元的实例数量
假设我有一个用 C# 编写的应用程序,名为 EquipCtrl.exe,它作为 PC 上的本地进程运行来控制一台设备。
显然,我希望每台 PC 上只运行一个 Equipctrl 实例。如果我每台 PC 有两个设备需要控制,那么我会将其限制为每台 PC 两个实例。
我所做的方法是其中之一 1. 进程名称。我将该进程命名为 EqCtrl,并在进程启动时,它会计算名称为“EqCtrl”的进程数。 2. 执行名称。启动时计算执行名称为 EquipCtrl.exe 的进程数。 3.登记记录。 4. SQL Server数据库记录。
对我来说,进程名称或执行名称检测是最简单的,也是我最常(如果不是全部)做的事情。但是,他们很容易发生名称冲突。即使我进一步找出执行路径,也可以通过将执行文件复制到另一个文件夹来规避该限制。
在 .NET 上执行执行限制的最佳方法是什么?为什么?注册表记录是最好的方法吗?
Let's say I have an application written in C# called EquipCtrl.exe which runs as a local process on a PC to control a piece of equipment.
Obviously, I would wish to have only one instance of Equipctrl to run on each PC. If I had two equip to control per PC, I would then limit it to two instances per PC.
The way I did is was either one of
1. Process name. I name the process EqCtrl and at process start-up, it would count the number processes with the name "EqCtrl".
2. Execution name. At start-up count the number of processes with the execution name EquipCtrl.exe.
3. Registry record.
4. SQL Server database record.
To me, process name or execution name detection is the simplest and what I do most (if not all) of the time. But, they are susceptible to name clashing. Even if I go further to find out the execution path, the limit could be circumvented by copying the execution file to another folder.
What is the best way to perform execution limiting on .NET? Why? Is registry record the best way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试系统范围的信号量:
http://msdn.microsoft.com/en-us/library /system.threading.semaphore.aspx
Try a system-wide Semaphore:
http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx
Scott Hanselman 的博客对此有一篇很棒的文章...
http://www.hanselman.com/blog /TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx
Scott Hanselman's Blog has a great post on this...
http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx
嗯..当我们只想允许应用程序的单个实例时,我们使用 命名mutex
这并不能完全实现您想要的场景。
另一点,为了避免冲突,除了可执行文件名称和目录之外,还要使用可执行文件的 MD5 哈希值。
Hmm .. when we want to allow only a single instance of an application we use a named mutex
That doesn't exactly enable the scenario you desire.
Another point, to avoid collisions, in addition to the executable name and directory, use an MD5 hash of the executable file.
您可以通过计数命名互斥量\信号量来做到这一点,还要确保您创建的互斥量/信号量前缀以 GLOBAL\ 和 LOCAL\ 开头,否则远程桌面连接将不会读取这些命名互斥量,并且计数将丢失。
http://msdn.microsoft.com/en-us/库/ms682411(VS.85).aspx
You can do this with counting named mutex\semaphore, also make sure the mutex/semaphore prefix you create starts with GLOBAL\ and LOCAL\ otherwise remote desktop connection won't read these named mutex and count will be lost.
http://msdn.microsoft.com/en-us/library/ms682411(VS.85).aspx