Csharp/C Sharp/Thread/Mutex

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

new Mutex

 

using System;
using System.Threading;

class NETMutex {
    static Mutex myMutex;
    public static void Main() {
        myMutex = new Mutex(true, "AAA");
        NETMutex nm = new NETMutex();
        Thread t = new Thread(new ThreadStart(nm.Run));
        t.Start();
        Thread.Sleep(5000);
        myMutex.ReleaseMutex();
        myMutex.WaitOne();
    }
    public void Run() {
        Console.WriteLine("In Run");
        myMutex.WaitOne();
        Console.WriteLine("Thread sleeping for 10 secs");
        Thread.Sleep(10000);
        Console.WriteLine("End of Run() method");
    }
}


new Mutex(false), WaitOne

 
using System;
using System.Threading;
   
class Database
{
    static Mutex mutex = new Mutex(false);
   
    public static void SaveData(string text)
    {
        mutex.WaitOne();
        Console.WriteLine("Database.SaveData - Started");
        Console.WriteLine("Database.SaveData - Working");
        for (int i = 0; i < 100; i++)
        {
            Console.Write(text);
        }
        Console.WriteLine("\nDatabase.SaveData - Ended");
        mutex.Close();
    }
}
   
class ThreadMutexApp{
    public static void WorkerThreadMethod1() {
        Console.WriteLine("Worker thread #1 - Started");
        Database.SaveData("x");
        Console.WriteLine("Worker thread #1 - Returned from Output");
    }
   
    public static void WorkerThreadMethod2() {
      Console.WriteLine("Worker thread #2 - Started");
      Database.SaveData("o");
      Console.WriteLine("Worker thread #2 - Returned from Output");
    }
   
    public static void Main() {
        ThreadStart worker1 = new ThreadStart(WorkerThreadMethod1);
        ThreadStart worker2 = new ThreadStart(WorkerThreadMethod2);
   
        Console.WriteLine("Main - Creating worker threads");
   
        Thread t1 = new Thread(worker1);
        Thread t2 = new Thread(worker2);
   
        t1.Start();
        t2.Start();
   
        Console.ReadLine();
    }
}


new Mutex(true, "MutexExample", out ownsMutex)), ReleaseMutex

 
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.");
            }
        }
    }
}