确保只有一个应用程序实例 [英] Ensuring only one application instance
问题描述
可能重复:
<一href="http://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-application">What是创建一个单实例应用程序的正确方法是什么?
我有一个WinForms应用程序,它通过以下code启动一个启动画面:
I have a Winforms app, which launches a splash screen via the following code:
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;
以上是在主窗体的codebehind从Load事件处理程序调用。
The above is in the main form's codebehind and called from the load event handler.
但是,我怎么能保证应用程序只有一个实例将加载的时间?在主窗体的Load事件处理程序,我可以检查进程列表是系统上(通过GetProcessesByName(...)),但有没有更好的方法?
However, how can I ensure that only one instance of the application will load at a time? In the load event handler of the main form, I could check if the process list is on the system (via GetProcessesByName(...)), but is there a better method?
使用.NET 3.5。
Using .NET 3.5.
推荐答案
GetProcessesByName是,如果另一个实例正在运行检查慢的方式。最快和优雅的方法是使用互斥:
GetProcessesByName is slow way of checking if another instance is running. The fastest and elegant method is using mutex:
[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
}
请也记住,c您的$ C $ presented是不是最好的方法。因为它被告知的意见调用DoEvents()在循环中是不是最好的主意。一个
Please also bear in mind that the code you presented is not the best approach. As it was advised in one of comments calling DoEvents() in a loop is not the best idea.
这篇关于确保只有一个应用程序实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!