且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查应用程序的另一个实例是否正在运行

更新时间:2023-10-20 17:12:16

想要一些严肃的代码?这里是.

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.