在.NET中,防止应用程序的多个实例同时运行的最佳方式是什么?如果没有“最佳”技术,那么对于每种解决方案都需要考虑哪些注意事项?
发布于 2008-09-18 16:38:20
使用互斥锁。上面的一个使用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";发布于 2008-09-18 16:16:04
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;
}发布于 2008-09-18 18:26:19
下面是确保只有一个实例在运行所需的代码。这是使用命名互斥锁的方法。
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();
}
}
}https://stackoverflow.com/questions/93989
复制相似问题