1

我想要一个可以跨进程共享的单例类。所以我很自然地在 .NET 4.0 中使用了 Mutex。

现在我有两个相同应用程序的实例正在运行。一个人修改了这个单例的“名称”属性,我想要的只是另一个应用程序来获取这个更改。但是即使在第一个实例释放 Mutex 之后,第二个实例也无法在 WaitOne 调用中成功。我想知道为什么以及我在下面的代码中做错了什么?请注意,入口点是方法 RunSingletonAcrossProcesses()。

这是我的单身课程

public class SingletonAcrossProcesses
{
    
private static SingletonAcrossProcesses _instance;
    
private static Mutex _mutex = new Mutex(true, @"Global\" + "sivablogz.wordpress.com SingletonMutexDemo");

    protected SingletonAcrossProcesses()
    {
    }

    public static SingletonAcrossProcesses GetInstance()
    {
        if (_mutex.WaitOne(TimeSpan.Zero, true))
        {
            if (_instance == null)
            {
                _instance = new SingletonAcrossProcesses();
            }
            _mutex.ReleaseMutex();
        }            
        
        return _instance;                            
    }

    public string Name { get; set; }

    public static void RunSingletonAcrossProcesses()
    {
        Console.WriteLine("Press any key to Instantiate the singleton...");
        Console.ReadLine();
        SingletonAcrossProcesses instance = SingletonAcrossProcesses.GetInstance();

        if (instance != null)
        {
            if (String.IsNullOrEmpty(instance.Name))
            {
                Console.WriteLine("Enter a name for the instance...");
                instance.Name = Console.ReadLine();
            }
            Console.WriteLine("The Instance name is: " + instance.Name);
        }
        else
            Console.WriteLine("The Singleton Instance could not be obtained.");            
        Console.WriteLine("Press any key to terminate...");
        Console.ReadLine();
    }
}

提前致谢,

湿婆

4

1 回答 1

1

你似乎遇到了这个:

如果 name 不为 null 并且 initialOwned 为 true,则调用线程仅在此调用创建了命名系统互斥锁时才拥有互斥锁。由于没有确定是否创建了命名系统互斥锁的机制,因此在调用此构造函数重载时最好为 initialOwned 指定 false。如果需要确定初始所有权,可以使用 Mutex(Boolean, String, Boolean) 构造函数。

见这里:http: //msdn.microsoft.com/en-us/library/f55ddskf.aspx

于 2013-07-10T06:45:31.257 回答