发布模式下的C#mutex与调试模式下的行为不同

nur*_*chi 6 c# debugging mutex release

所以我有以下代码:

...
private static void Main(string[] args)
{
    string file=DateTime.Now.ToFileTime().ToString();
    File.AppendAllText(file, "Mutex\r\n");

    bool CreatedNew;
    Mutex mutex=new Mutex(true, AppDomain.CurrentDomain.FriendlyName, out CreatedNew);

    if(CreatedNew)
    {
        #if DEBUG
        File.AppendAllText(file, "Launching in DEBUG mode\r\n");
        #else
        File.AppendAllText(file, "Launching in RELEASE mode\r\n");
        #endif

        //Program.Launch();
        Program.ProcessArgsAndLaunch(args);
    }
    else
    {
        File.AppendAllText(file, "Handling dupe\r\n");
        Program.HandleDuplicate();
    }
}
...
Run Code Online (Sandbox Code Playgroud)

我在这里检查了无数文章,其他网站没有运气.

基本上,代码检查应用程序的运行实例,如果有,则切换到正在运行的实例的主窗口.如果没有,它会启动应用程序.

Debug模式下,它都按预期工作,当我将配置切换到时,问题就开始了Release:应用程序始终启动(Mutex似乎什么都不做).

我添加了条件编译的转储,显示应用程序在哪种模式下启动,输出根据配置进行更改,但遗憾的是,应用程序的行为也是如此.

这可能是一个,race condition但我不确定.

如果需要,将发布更多代码.

谢谢.

Jon*_*eet 13

与Juan的答案一起,在调试器内部和外部启动之间的垃圾收集方面存在差异.这与Debug配置和Release配置并不完全相同,但无论如何你都应该注意这一点.

在调试器中,局部变量将充当其整个范围的GC根目录 - 但是当您没有调试时,您的mutex变量根本不是GC根,因为在初始化之后您不使用它.这意味着您Mutex可以立即收集垃圾(因此将释放本机互斥锁).

您应该使用using声明在适当的时间明确处置Mutex:

// Note that you don't need a variable here... you can have one if you
// want though
using (new Mutex(...))
{
    // Code here to be executed while holding the mutex
}
Run Code Online (Sandbox Code Playgroud)


Jua*_*pes 8

如果有一个实例作为Debug运行,另一个实例作为Release运行,则它们不会共享相同的互斥锁,因为AppDomain.CurrentDomain.FriendlyName根据托管进程是否处于活动状态而不同.

如下所示:http://msdn.microsoft.com/en-us/library/ms242202.aspx