使用Mutex运行应用程序的单个实例
为了仅允许正在运行的应用程序的单个实例使用互斥锁。 代码如下。 这是做到这一点的正确方法吗? 代码中是否有缺陷?
当用户第二次尝试打开应用程序时如何显示已经运行的应用程序。 目前(在下面的代码中),我只是显示另一个实例已经运行的消息。
static void Main(string[] args)
{
Mutex _mut = null;
try
{
_mut = Mutex.OpenExisting(AppDomain.CurrentDomain.FriendlyName);
}
catch
{
//handler to be written
}
if (_mut == null)
{
_mut = new Mutex(false, AppDomain.CurrentDomain.FriendlyName);
}
else
{
_mut.Close();
MessageBox.Show("Instance already running");
}
}
我这样做了一次,我希望这会有所帮助:
bool createdNew;
Mutex m = new Mutex(true, "myApp", out createdNew);
if (!createdNew)
{
// myApp is already running...
MessageBox.Show("myApp is already running!", "Multiple Instances");
return;
}
static void Main()
{
using(Mutex mutex = new Mutex(false, @"Global" + appGuid))
{
if(!mutex.WaitOne(0, false))
{
MessageBox.Show("Instance already running");
return;
}
GC.Collect();
Application.Run(new Form1());
}
}
资料来源:http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx
我使用这个:
private static Mutex _mutex;
private static bool IsSingleInstance()
{
_mutex = new Mutex(false, _mutexName);
// keep the mutex reference alive until the normal
//termination of the program
GC.KeepAlive(_mutex);
try
{
return _mutex.WaitOne(0, false);
}
catch (AbandonedMutexException)
{
// if one thread acquires a Mutex object
//that another thread has abandoned
//by exiting without releasing it
_mutex.ReleaseMutex();
return _mutex.WaitOne(0, false);
}
}
public Form1()
{
if (!isSingleInstance())
{
MessageBox.Show("Instance already running");
this.Close();
return;
}
//program body here
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (_mutex != null)
{
_mutex.ReleaseMutex();
}
}
链接地址: http://www.djcxy.com/p/51157.html
上一篇: Run single instance of an application using Mutex
下一篇: How do I prevent my app from launching over and over again