如何检查应用程序的另一个实例是否正在运行 [英] How to check if another instance of the application is running
问题描述
有人可以展示如何检查程序的另一个实例(例如 test.exe)是否正在运行,如果存在,则停止加载应用程序.
想要一些严肃的代码?这里是.
var exists = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() >1;
这适用于任何应用程序(任何名称),如果另一个实例运行相同应用程序,它将成为true
.>
要解决您的需求,您可以使用以下任一方法:
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) return;
从您的 Main 方法退出该方法...或
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) System.Diagnostics.Process.GetCurrentProcess().Kill();
这将立即终止当前加载进程.
<小时>您需要为 .Count()
扩展方法.或者,您可以使用 .Length
属性.
Could someone show how it is possible to check whether another instance of the program (e.g. test.exe) is running and if so stop the application from loading if there is an existing instance of it.
Want some serious code? Here it is.
var exists = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1;
This works for any application (any name) and will become true
if there is another instance running of the same application.
Edit: To fix your needs you can use either of these:
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) return;
from your Main method to quit the method... OR
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) System.Diagnostics.Process.GetCurrentProcess().Kill();
which will kill the currently loading process instantly.
You need to add a reference to System.Core.dll for the .Count()
extension method. Alternatively, you can use the .Length
property.
这篇关于如何检查应用程序的另一个实例是否正在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!