[英]What is the safest way to prevent multiple instances of a program?
I am trying to prevent my program from running multiple instances at any given time. 我试图阻止我的程序在任何给定时间运行多个实例。 I have read about using mutex and windows events, however both threads were several years old, and I'm curious if with .net4 there is a more simple, and more elegant way to deal with this?
我已经阅读过有关使用互斥锁和Windows事件的内容,但是两个线程都已经存在了几年,我很好奇是否有.net4有更简单,更优雅的方式来处理这个问题? I thought I had read about a setting for the form that allowed you to deny multiple instances by the property?
我以为我读过有关表单的设置,允许您拒绝该属性的多个实例? Could someone shed some light on what the safest and/or simplest way to prevent multiple instances of a program is?
有人可以说明防止多个程序实例最安全和/或最简单的方法是什么?
The safest way is to use the built-in support in .NET, WindowsFormsApplicationBase.IsSingleInstance property. 最安全的方法是使用.NET,WindowsFormsApplicationBase.IsSingleInstance属性中的内置支持。 Hard to guess if it is appropriate, you didn't make much effort describing your exact needs.
很难猜测它是否合适,你没有花太多精力描述你的确切需求。 And no, nothing changed in the past 5 years.
不,过去5年没有任何改变。 – Hans Passant Jan 7 at 0:38
- Hans Passant 1月7日0:38
This was the best answer but Hans didn't submit it as an answer. 这是最好的答案,但汉斯没有提交答案。
In VB you can set this at the project level (Properties > General) for Winforms projects. 在VB中,您可以在Winforms项目的项目级别(“属性”>“常规”)中进行设置。
In C# you can use code similar to this.. needs conversion of course.. 在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
Whoops, I forgot to mention that you will need to place GC.KeepAlive(tSingleInstanceMutex)
after your Application.Run() call 哎呀,我忘了提到你需要在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.