Csharp/C Sharp by API/System.Threading/Mutex

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Mutex.ReleaseMutex()

<source lang="csharp"> using System; using System.Threading; class MainClass {

   public static void Main() {
       bool ownsMutex;
       using (Mutex mutex = new Mutex(true, "MutexExample", out ownsMutex)) {
           if (ownsMutex) {
               Console.ReadLine();
               mutex.ReleaseMutex();
           } else {
               Console.WriteLine("Another instance of this application " +
                   " already owns the mutex named MutexExample.");
           }
       }
   }

}


 </source>


Mutex.WaitOne()

<source lang="csharp"> using System; using System.Threading; public class MainClass {

 private static int Runs = 0;
 static Mutex mtx;
 public static void CountUp() 
 {
   while (Runs < 10)
   {
     mtx.WaitOne();
     int Temp = Runs;
     Temp++;
     Console.WriteLine(Thread.CurrentThread.Name + " " + Temp);
     Thread.Sleep(1000);
     Runs = Temp;
     mtx.ReleaseMutex();
   } 
 }
 public static void Main() 
 {
   mtx = new Mutex(false, "RunsMutex");
   Thread t2 = new Thread(new ThreadStart(CountUp));
   t2.Name = "t2";
   Thread t3 = new Thread(new ThreadStart(CountUp));
   t3.Name = "t3";
   t2.Start();
   t3.Start();
 }

}


 </source>