C#已存在与错误_等效的互斥锁

C#已存在与错误_等效的互斥锁,c#,C#,我正在尝试创建一个跨进程互斥体,并确保只有一个实例正在运行 我将这些代码放在Main方法中并启动了两个进程,但第二个进程没有立即退出: string name = "Global\\qweqwe"; try { new Mutex(true, name); } catch (Exception) { Console.WriteLine("Mutex already exists"); return; } 然后我切换到pinvoke,它起了作用: string name

我正在尝试创建一个跨进程互斥体,并确保只有一个实例正在运行

我将这些代码放在Main方法中并启动了两个进程,但第二个进程没有立即退出:

string name = "Global\\qweqwe";

try {
    new Mutex(true, name);
} catch (Exception) {
    Console.WriteLine("Mutex already exists");
    return;
}
然后我切换到pinvoke,它起了作用:

string name = "Global\\qweqwe";

IntPtr mutex = CreateMutex(IntPtr.Zero, true, name);
if (mutex == IntPtr.Zero)
{
    return;
}

if (Marshal.GetLastWin32Error() == ERROR_ALREADY_EXISTS)
{
    Debug.WriteLine("mutex already exists");
    return;
}
C代码怎么了


注意:我没有释放互斥锁,因为这是一个最小的情况。

您可以使用此代码检查互斥锁是否已经存在并关闭进程

var mutex=new mutex(false,name,out bool createdNew);
如果(!createdNew)
{
//已经创建
}
另一个选项是使用方法并传递一些超时,如本文所示

var mutex=new mutex(false,name);
if(mutex.WaitOne(TimeSpan.Zero))
{
//没有创建
}
其他的
{
//已存在,创建了一个实例
}
还有一个很好的单实例应用程序。它很古老,与WinForms相关,但其思想是相同的。

我个人在c#中使用的是app.cs中的eventwaithandle

public static EventWaitHandle ApplicationMutex { get; set; }



        /// <summary>Handles the application startup sequence</summary>
        /// <param name="sender">The App.xaml file</param>
        /// <param name="e"><see cref="StartupEventArgs"></see></param>
        private async void Application_Startup(object sender, StartupEventArgs e) {
            var appName = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule?.FileName);

            // We create a mutex here that lasts for the lifetime of our program to stop users from
            // opening two windows at once
            ApplicationMutex = new EventWaitHandle(false, EventResetMode.ManualReset, appName, out var created);

            if (!created) {

                if (ApplicationMutex != null)
                    Log.Error("Failed to create mutex");

                Current.Shutdown();
            }


这正是您希望它做的

那么,实际发生的情况是什么呢删除了cpp tag当您可以让编译器完成工作时,为什么要使用互斥锁?使用锁块并锁定类中的某个对象
 ~MainWindow() {
            App.ApplicationMutex.Dispose();
        }