一个同步基元,也可用于进程间同步。
即进程同步 当然也可以线程同步
所以在线程同步角度来说,Monitor开销小,优于Mutex,
要实现进程同步,Monitor也干不了,Mutex是首选。
MSDN 实例:
This example shows how a Mutex is used to synchronize access
to a protected resource. Unlike Monitor, Mutex can be used with
WaitHandle.WaitAll and WaitAny, and can be passed across
AppDomain boundaries.
using System; using System.Threading; class Test { // Create a new Mutex. The creating thread does not own the // Mutex. private static Mutex mut = new Mutex(); private const int numIterations = 1; private const int numThreads = 3; static void Main() { // Create the threads that will use the protected resource. for(int i = 0; i < numThreads; i++) { Thread myThread = new Thread(new ThreadStart(MyThreadProc)); myThread.Name = String.Format("Thread{0}", i + 1); myThread.Start(); } // The main thread exits, but the application continues to // run until all foreground threads have exited. } private static void MyThreadProc() { for(int i = 0; i < numIterations; i++) { UseResource(); } } // This method represents a resource that must be synchronized // so that only one thread at a time can enter. private static void UseResource() { // Wait until it is safe to enter. mut.WaitOne(); Console.WriteLine("{0} has entered the protected area", Thread.CurrentThread.Name); // Place code to access non-reentrant resources here. // Simulate some work. Thread.Sleep(500); Console.WriteLine("{0} is leaving the protected area ", Thread.CurrentThread.Name); // Release the Mutex. mut.ReleaseMutex(); } }
class Program { static void Main(string[] args) { for (int i = 0; i < 20; i++) { Thread t = new Thread(Run); t.Start(); } Console.Read(); } static int count = 0; static Mutex mutex = new Mutex(); static void Run() { Thread.Sleep(100); mutex.WaitOne(); Console.WriteLine("当前数字:{0}", ++count); mutex.ReleaseMutex(); } }
进程同步运行2个exe实例:
class Program { static void Main(string[] args) { Thread t = new Thread(Run); t.Start(); Console.Read(); } static Mutex mutex = new Mutex(false, "tsp"); static void Run() { mutex.WaitOne(); Console.WriteLine("当前时间:{0}我是线程:{1},我已经进去临界区", DateTime.Now, Thread.CurrentThread.GetHashCode()); Thread.Sleep(10000); Console.WriteLine(" 当前时间:{0}我是线程:{1},我准备退出临界区", DateTime.Now, Thread.CurrentThread.GetHashCode()); mutex.ReleaseMutex(); } }
延伸 同理 一个运行程序只希望启动一个实例:
查看msdn
public partial class App : System.Windows.Application { Mutex mutex; public App() { this.Startup += new StartupEventHandler(App_Startup); } void App_Startup(object sender, StartupEventArgs e) { bool ret; mutex = new Mutex(false, Process.GetCurrentProcess().ProcessName, out ret); if (!ret) { MessageBox.Show("程序已打开", "", MessageBoxButton.OK, MessageBoxImage.Stop); Environment.Exit(0); } } }