Mutex
Mutex的工作原理与lock关键字基本相同,因此在这里就不多介绍。但Mutex与lock和Monitor的最大不同在于其可以作用于多个进程,可以提供进程间同步。
单实例运行
Mutex一个最广泛的运用就是使程序只能有一个实例在运行。下面这段代码实现了单实例运行,先打开一个实例,再打开一个实例时由于前面实例的存在则会直接退出。
using System;
using System.Threading;
namespace MutexTest
{
class Program
{
//start out with un-owned mutex
static Mutex mutex = new Mutex(false,"MutexTest");
static void Main(string[] args)
{
//check to see if there is another instance, allow 5 secs
//another instance may be in process of closing right now
if(!mutex.WaitOne(TimeSpan.FromSeconds(5)))
{
Console.WriteLine("MutexTest already running! Exiting");
return;
}
try
{
Console.WriteLine("MutexTest Started");
Console.ReadLine();
}
finally
{
//release the mutx to allow, possible future instance to run
mutex.ReleaseMutex();
}
}
}
}
打开第一个实例:
打开第二个实例(失败):