防止C#应用程序运行多个实例 [英] prevent a c# application from running more than one instance

查看:50
本文介绍了防止C#应用程序运行多个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用C#编写了一个程序现在我想知道如果该程序已经在运行,则阻止该程序启动的正确方法是什么?

I wrote a program in c# now I would like to know what is the proper way to prevent the program from starting if it is already running?

因此,如果它已经在运行,则双击该程序将因为它已经在运行而无法启动.

so if it is already running, and double-click on the program it will not start because it is already running.

我可以做到,但是我在考虑一种标准且正确的方法.

I can do that, but I was thinking of a standard and proper way.

推荐答案

推荐的方法是使用系统互斥锁.

The recommended way to do this is with a system mutex.

bool createdNew;
using(var mutex = new System.Threading.Mutex(true, "MyAppName", out createdNew))
{
    if (createdNew)
        // first instance
        Application.Run();
    else
        MessageBox.Show("There is already an instace running");
}

Mutex ctor的第一个参数告诉它为此线程创建一个系统范围的互斥量.如果Mutex已经存在,它将通过第三个参数返回 false .

The first parameter to the Mutex ctor tells it to give create a system wide mutex for this thread. If the Mutex already exists it will return out false through the 3rd parameter.

更新
放在哪里?我将其放在program.cs中.如果将其放在form_load中,则需要在应用程序的生命周期内保留互斥锁(将互斥锁作为表单的成员),并在表单卸载时手动释放它.
越早调用此方法越好,在其他应用打开数据库连接等之前,以及在为表单/控件创建资源之前.

Update
Where to put this? I'd put this in program.cs. If you put it in form_load you'll need to keep the mutex for the life time of the application (have the mutex as a member on the form), and manually release it in the form unload.
The earlier you call this the better, before the other app opens DB connections etc. and before resources are put created for forms / controlls etc.

这篇关于防止C#应用程序运行多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆