【发布时间】:2014-12-03 13:39:20
【问题描述】:
在 Program.cs 中我做了:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using DannyGeneral;
namespace mws
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
try
{
if (IsApplicationAlreadyRunning() == true)
{
MessageBox.Show("The application is already running");
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
catch (Exception err)
{
Logger.Write("error " + err.ToString());
}
}
static bool IsApplicationAlreadyRunning()
{
string proc = Process.GetCurrentProcess().ProcessName;
Process[] processes = Process.GetProcessesByName(proc);
if (processes.Length > 1)
{
return true;
}
else
{
return false;
}
}
}
}
我使用了断点,即使我从 Visual Studio 中关闭了我的程序并尝试再次运行应用程序,它也会返回 true 并抛出应用程序已经运行的消息。
在断点中我看到变量 proc 包含:My Weather Station.vshost
现在我注意到只有当我在新的 Visual Studio 窗口中打开我的应用程序的另一个副本并且该应用程序位于另一个硬盘上的另一个位置并且我没有在任何 Visual Studio 上运行该应用程序时才会发生这种情况窗户。
那么为什么当我在 Visual Studio 中打开两次相同的应用程序并且它没有运行时它认为它正在运行? 即使我关闭了第二个视觉工作室,我仍然会在 proc My Weather Station.vshost 中看到,但这次它返回 false。
编辑
我现在看到变量 processes 在索引 0 和 1 中包含两次 My Weather Station.vshost 如果我关闭第二个视觉工作室,它只包含一个。
问题是 My Weather Station.vshost 是什么?如果应用程序未运行,为什么将其视为正在运行的应用程序?我怎样才能更好地进行检查,这样如果我打开我的应用程序的更多副本,它就不会认为该应用程序正在运行?
我想打开另一个应用程序副本的原因是第二个应用程序较旧,我想看看我做过的一些旧事情。
我可以改变这个:
if (processes.Length > 1)
例如,使其 > 10 但我仍然不明白 My Weather Station.vshost 是什么?为什么它在内存中运行?以及为什么将其视为正在运行的应用程序?
【问题讨论】:
-
如果您要确保只有 1 个实例正在运行,请尝试此线程
http://stackoverflow.com/questions/184084/how-to-force-c-sharp-net-app-to-run-only-one-instance-in-windows -
这是我使用的 - 对我有用:stackoverflow.com/questions/25538524/…