可能的重复:
创建单实例应用程序的正确方法是什么? https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application
我有一个 Winforms 应用程序,它通过以下代码启动启动屏幕:
Hide();
bool done = false;
// Below is a closure which will work with outer variables.
ThreadPool.QueueUserWorkItem(x =>
{
using (var splashForm = new SplashScreen())
{
splashForm.Show();
while (!done)
Application.DoEvents();
splashForm.Close();
}
});
Thread.Sleep(3000);
done = true;
上面的代码位于主窗体的代码隐藏中,并从加载事件处理程序中调用。
但是,如何确保一次仅加载应用程序的一个实例?在主窗体的加载事件处理程序中,我可以检查进程列表是否在系统上(通过 GetProcessesByName(...)),但是有更好的方法吗?
使用.NET 3.5。
GetProcessesByName 是检查另一个实例是否正在运行的缓慢方法。最快且优雅的方法是使用互斥锁:
[STAThread]
static void Main()
{
bool result;
var mutex = new System.Threading.Mutex(true, "UniqueAppId", out result);
if (!result)
{
MessageBox.Show("Another instance is already running.");
return;
}
Application.Run(new Form1());
GC.KeepAlive(mutex); // mutex shouldn't be released - important line
}
另请记住,您提供的代码并不是最好的方法。正如评论之一所建议的那样,在循环中调用 DoEvents() 并不是最好的主意。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)