c# - 如何确定某个位置的 .NET 应用程序实例是否正在运行?

标签 c# .net windows mutex

我需要禁止从同一文件夹启动的应用程序,但如果同一应用程序从其他文件夹运行则允许它。

问题是当应用程序关闭时,它变得不可见但仍然在内存中,因为它终止了一些内部作业。

当旧实例仍在内存中终止时,用户很可能会从同一文件夹快速再次启动此应用程序。

但从另一方面来看,如果此应用程序从其他文件夹运行,应该是可能的。

有什么线索可以用 C# 实现吗?


更新:

1

事实上,应用程序将一些日志写入子目录中的本地文件以及本地数据库文件中。所以这很可能是两个实例之间的一些冲突。

2

 Guid appGuid = Guid.Parse("305BACEA-4074-11E1-85E1-066E4854019B");

        public MainWindow()
        {
            InitializeComponent();


            using (Mutex mutex = new Mutex(false, @"Global\" + appGuid) )
            {

                if (!mutex.WaitOne(0, false))
                {
                    // MessageBox.Show("Instance already running");

                    // Somehow here I have to get the path of the running instance.
                    // If the path the same as the current instance has I have do ban starting instance.

                    return;
                }

                GC.Collect();              
            }

最佳答案

谢谢大家!

最后基于这个post我找到了解决方案:

public partial class App : Application
    {
        private Mutex _instanceMutex = null;

        protected override void OnStartup(StartupEventArgs e)
        {

            string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).Replace("\\", ".");

            // check that there is only one instance of the control panel running...
            bool createdNew;
            _instanceMutex = new Mutex(true, path, out createdNew);
            if (!createdNew)
            {
                _instanceMutex = null;
                MessageBox.Show("Instance already running");
                Application.Current.Shutdown();
                return;
            }

            base.OnStartup(e);
        }

        protected override void OnExit(ExitEventArgs e)
        {
            if (_instanceMutex != null)
                _instanceMutex.ReleaseMutex();
            base.OnExit(e);
        }

}

关于c# - 如何确定某个位置的 .NET 应用程序实例是否正在运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8884499/

相关文章:

c# - 使用 WindowsImpersonationContext 模拟当前用户访问网络驱动器

c# - 逆向工程串行通信

java - 如何通过 JNA 检查全局可逆加密?

java - 我可以在不安装 Ask 工具栏的情况下静默安装 Java JRE 吗?

c# - 带有大量嵌套列表的列表上的 LINQ

c# - 使用 EF 和 Dot Net Core 1(PostgreSQL 数据库)生成迁移时出错

c# - 是否可以使用 Autodesk.AutoCAD.Interop 在 AutoCAD 中编辑 block 属性?

c# - 选择其中一个功能

C#/.NET Timers 和 Win32 Sleep 函数都不准确

c# - 如何在 ASP.NET 中实现支付网关