c# - 在 C# 控制台应用程序中检查的 Delphi 应用程序中打开的互斥量

标签 c# .net delphi c#-4.0 delphi-10.1-berlin

我正在启动一个 Delphi 应用程序并为其创建一个互斥量,如下所示:

var
  AMutex: THandle;

function OpenMutex(const AMutexName: String): Boolean;
begin

  { Assume the Windows Mutext is already open }
  Result := False;

  { Is the Mutex already open? }
  if AMutex <> 0 then
    exit;

  { Try to create Windows Mutex }
  if CreateProgramMutex( AMutexName , AMutex) then
    Result := True
  else
    AMutex := 0;
end;

 function CreateProgramMutex( AMutexName: string; var AMutex: THandle ): boolean;
begin
    { Assume the new program mutex was created successfully. }
    Result := true;

    { Attempt to create a new mutex. }
    AMutex := CreateMutex(nil, False, PChar(AMutexName));

    { If we at least got a handle to the mutex... }
    if (AMutex <> 0) then
    begin

      if GetLastError = ERROR_ALREADY_EXISTS then begin
        { Close the handle, since it already exists. }
        CloseHandle(AMutex);

        { Set the return to show that it was already running. }
        Result := false;
      end;
    end else
      Result := false;
end;

我正在尝试从 C#(作为初学者)查明我的应用程序是否已经在控制台应用程序中运行:

using System;
using System.Threading;

namespace ConsoleApplication1
{
    class OneAtATimePlease
    {
        private static Mutex _mutex;

        private static bool IsSingleInstance()
        {
            _mutex = new Mutex(false, "my mutex name");

            // keep the mutex reference alive until the normal 
            //termination of the program
            GC.KeepAlive(_mutex);

            try
            {
                return _mutex.WaitOne(0, false);
            }
            catch (AbandonedMutexException)
            {
                // if one thread acquires a Mutex object 
                //that another thread has abandoned 
                //by exiting without releasing it

                _mutex.ReleaseMutex();
                return _mutex.WaitOne(0, false);
            }
        }
        static void Main()
        {
            if (!IsSingleInstance())
                Console.WriteLine("already running");
            Console.ReadLine();

        }
    }
}

即使 Delphi 应用程序正在运行,IsSingleInstance 也会返回 true。使用相同的 Delphi 代码检查 Delphi 控制台应用程序中的互斥量是有效的。我确定这很明显,但我无法弄清楚我做错了什么。

PS: 一切都是在同一个 Windows 用户 session 下完成的

最佳答案

您说您的目标是检查外部应用程序是否正在运行(通过使用命名的互斥体)。那么,对于这种情况,您不应该尝试在您的应用程序中创建给定名称的互斥对象,而只是尝试打开它。原因很简单,如果那个外部应用程序使用这样的互斥锁来检查它是否在自己运行,你实际上会为你的应用程序窃取这个互斥锁,而那个外部应用程序将永远不会启动。

为了您的目的,请使用 TryOpenExisting类函数。例如:

using System;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Mutex mutex;

            if (Mutex.TryOpenExisting("My unique mutex name", out mutex)) {
                try {
                    // with the used TryOpenExisting overload you can work with
                    // the mutex object here; you can wait for it or release
                    Console.WriteLine("Application is running!");
                }
                finally {
                    mutex.Close();
                }
            }
            else {
                Console.WriteLine("Application is NOT running!");
            }
            Console.ReadLine();
        }
    }
}

关于c# - 在 C# 控制台应用程序中检查的 Delphi 应用程序中打开的互斥量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50929190/

相关文章:

c# - 如何在运行时检查操作系统版本,例如在 Windows 或 Linux 上,不使用条件编译语句

c# - 在 GTK# Image Widget 中显示动画 GIF

.net - 从 vb.net 中的可变长度字符串中提取最后 10 个字符

delphi - 如何使用 UIB-Unified Interbase (http ://www. progdigy.com/?page_id=5) 直接与数据交互?

C# 反射 : How to get the type of a Nullable<int>?

c# - 为什么 ref 参数不是逆变的?

c# - 带秒的时间选择器

c# - ObjectPool<T> 或类似的 .NET 已经在库中了吗?

delphi - 为什么源文件创建时间戳会在保存时更新?

delphi - 为什么 TRichEdit 在转换为明文时会插入 RTF 代码中没有的换行符?