【问题标题】:I'm checking if my application is already running or not and it's saying running even if i stopped the application why?我正在检查我的应用程序是否已经在运行,即使我停止了应用程序,它仍然在运行,为什么?
【发布时间】: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 是什么?为什么它在内存中运行?以及为什么将其视为正在运行的应用程序?

【问题讨论】:

标签: c# .net winforms


【解决方案1】:

您似乎正在尝试创建“单实例应用程序”。为此发布了几个现有的解决方案。普遍接受的方法是使用互斥体并查看它是否已被持有,如下所示: What is the correct way to create a single-instance application?

此外,这似乎是 Windows 窗体中已内置的一项功能(基于您的示例源文件中的引用,您似乎使用了该功能)。参考Prevent application launch if already running

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多