在.NET中,防止应用程序的多个实例同时运行的最佳方法是什么?如果没有"最佳"技术,每种解决方案需要考虑哪些注意事项?
小智 148
使用互斥锁.上面使用GetProcessByName的一个例子有很多警告.这是一篇关于这个主题的好文章:
http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx
[STAThread]
static void Main()
{
using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))
{
if(!mutex.WaitOne(0, false))
{
MessageBox.Show("Instance already running");
return;
}
Application.Run(new Form1());
}
}
private static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";
Run Code Online (Sandbox Code Playgroud)
小智 19
if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
{
AppLog.Write("Application XXXX already running. Only one instance of this application is allowed", AppLog.LogMessageType.Warn);
return;
}
Run Code Online (Sandbox Code Playgroud)
Sei*_*bar 18
以下是确保只运行一个实例所需的代码.这是使用命名互斥锁的方法.
public class Program
{
static System.Threading.Mutex singleton = new Mutex(true, "My App Name");
static void Main(string[] args)
{
if (!singleton.WaitOne(TimeSpan.Zero, true))
{
//there is already another instance running!
Application.Exit();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在尝试了多种解决方案后,我的问题出现了。我最终在这里使用了WPF的示例:http ://www.c-sharpcorner.com/UploadFile/f9f215/how-to-restrict-the-application-to-just-one-instance/
public partial class App : Application
{
private static Mutex _mutex = null;
protected override void OnStartup(StartupEventArgs e)
{
const string appName = "MyAppName";
bool createdNew;
_mutex = new Mutex(true, appName, out createdNew);
if (!createdNew)
{
//app is already running! Exiting the application
Application.Current.Shutdown();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在 App.xaml 中:
x:Class="*YourNameSpace*.App"
StartupUri="MainWindow.xaml"
Startup="App_Startup"
Run Code Online (Sandbox Code Playgroud)
小智 6
1 - 在 program.cs 中创建一个引用 ->
using System.Diagnostics;
Run Code Online (Sandbox Code Playgroud)
2 -void Main()作为第一行代码放入->
if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length >1)
return;
Run Code Online (Sandbox Code Playgroud)
就是这样。
听起来到目前为止已经提出了3种基本技术.
我错过了任何警告?
我在这里尝试了所有解决方案,但在我的 C# .net 4.0 项目中没有任何效果。希望能帮助这里的人找到对我有用的解决方案:
作为主类变量:
private static string appGuid = "WRITE AN UNIQUE GUID HERE";
private static Mutex mutex;
Run Code Online (Sandbox Code Playgroud)
当您需要检查应用程序是否已在运行时:
bool mutexCreated;
mutex = new Mutex(true, "Global\\" + appGuid, out mutexCreated);
if (mutexCreated)
mutex.ReleaseMutex();
if (!mutexCreated)
{
//App is already running, close this!
Environment.Exit(0); //i used this because its a console app
}
Run Code Online (Sandbox Code Playgroud)
我只需要在某些条件下关闭其他实例,这对我的目的很有效