2012-08-09 52 views
0

如果我做的:无法同步两个线程

ConsoleApp1:

bool mutexCreated; 
    var mutex = new Mutex(true, "MemoryMappedFileMutex", out mutexCreated); 

    Console.Write("Run Console App2 then press enter"); 
    Console.Read(); 

    // do work 
    Thread.Sleep(5000); 

    mutex.ReleaseMutex(); // makes console app 2 to stop waiting 

ConsoleApp2

var mutex = Mutex.OpenExisting("MemoryMappedFileMutex"); 

    mutex.WaitOne(); 

    // continue executing once console app 1 releases mutex 

一切都很正常。我必须先启动consoleApp1,然后才能使用此算法。

现在我的问题是我会喜欢consoleApp2充当服务器。因此,我希望首先启动该应用程序。问题是,如果我这样做:

bool mutexCreated; 
    var mutex = new Mutex(true, "MemoryMappedFileMutex", out mutexCreated); 

    mutex.WaitOne(); // <------ mutex will not wait why???? 

如果我这样做mutex.WaitOne()线程不会等待。换句话说,我想首先启动consoleApp2并让该应用程序等待,直到我以某种方式在控制台应用程序1上发出互斥信号。......

+0

不要调用你的互斥锁“MemoryMappedFileMutex”。互斥体名称是全球性的。您冒着与使用该通用名称的其他程序相冲突的风险。 – usr 2012-08-09 21:34:49

回答

1

在您的服务器应用程序中,尝试使用false作为第一个参数调用构造函数,以便调用线程最初不会拥有互斥锁。

1

等待来自拥有线程的互斥体不会阻塞,并且您指定true作为第一个互斥体构造函数arg,这表明它已被创建为当前线程所拥有。