繁体   English   中英

防止程序多个实例最安全的方法是什么?

[英]What is the safest way to prevent multiple instances of a program?

我试图阻止我的程序在任何给定时间运行多个实例。 我已经阅读过有关使用互斥锁和Windows事件的内容,但是两个线程都已经存在了几年,我很好奇是否有.net4有更简单,更优雅的方式来处理这个问题? 我以为我读过有关表单的设置,允许您拒绝该属性的多个实例? 有人可以说明防止多个程序实例最安全和/或最简单的方法是什么?

最安全的方法是使用.NET,WindowsFormsApplicationBase.IsSingleInstance属性中的内置支持。 很难猜测它是否合适,你没有花太多精力描述你的确切需求。 不,过去5年没有任何改变。 - Hans Passant 1月7日0:38

这是最好的答案,但汉斯没有提交答案。

在VB中,您可以在Winforms项目的项目级别(“属性”>“常规”)中进行设置。

在C#中你可以使用类似于此的代码..当然需要转换..

Dim tGrantedMutexOwnership As Boolean = False
Dim tSingleInstanceMutex As Mutex = New Mutex(True, "MUTEX NAME HERE", tGrantedMutexOwnership)

If Not tGrantedMutexOwnership Then
'
' Application is already running, so shut down this instance
'
Else
' 
' No other instances are running
'
End If

哎呀,我忘了提到你需要在Application.Run()调用之后放置GC.KeepAlive(tSingleInstanceMutex)

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;

namespace YourNameSpaceGoesHere
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {

            if (Process.GetProcessesByName("YourFriendlyProcessNameGoesHere").Length > 1)
            {
                MessageBox.Show(Application.ProductName + " already running!");
                Application.ExitThread();
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new YourStartUpObjectFormNameGoesHere());
            }

        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM