首页 > 解决方案 > 在 C# 控制台应用程序中检查的 Delphi 应用程序中打开的互斥锁

问题描述

我正在启动一个 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 用户会话下完成

标签: c#.netdelphic#-4.0delphi-10.1-berlin

解决方案


我认为您需要检查互斥锁是否存在或已创建。

Mutex appMutex = new Mutex(true, "MyMutex", out exclusive);
if (!exclusive)
{
  //Instance already existed
}

推荐阅读