C# Source Code: Using the Mutex object to guard resources across AppDomains
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Using the Mutex object to guard resources across AppDomains
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Friday, April 09, 2004
Hits:
1574
Category:
Unspecified
Article:
The Mutex class (mutual exclusion) is used to allow at most one thread access to a resource. Although this can be used as a simple locking tool to protect code regions, its principly designed to guard resources that can be shared across AppDomains or processes. The example below shows how the Mutex object can be used across multiple threads, but the same principles apply when creating a Mutex across AppDomains: using System; using System.Threading; //Copyright Andrew Baker (www.vbusers.com) namespace vbUsers.Threading { //This class demonstrates how to use a mutex (mutual exclusion) class to guard resources //that can be shared across threads and AppDomains class DemoMutex { static bool zbMutexAcquired = false; static Mutex instanceMutex = null; [STAThread] static void Main(string[] args) { Console.WriteLine("Thread {0}. Application Started...",AppDomain.GetCurrentThreadId()); //Grab Mutex AcquireMutex(); //Try and reaquire the mutex in a new thread Thread th1 = new Thread(new ThreadStart(AcquireMutex)); th1.Start(); //Wait for thread to finish th1.Join(); th1=null; //Release the Mutex in this thread and try again Console.WriteLine("Thread {0}. Releasing Mutex",AppDomain.GetCurrentThreadId()); Mutex Mutex1 = new Mutex(false, "vbusers.AppSingleInstance"); Mutex1.ReleaseMutex(); //Retry and reaquire the mutex in a new thread th1 = new Thread(new ThreadStart(AcquireMutex)); th1.Start(); //Wait for thread to finish th1.Join(); //Now create the mutex in this thread and retry again Console.WriteLine("Thread {0}. Grabbing Mutex",AppDomain.GetCurrentThreadId()); AcquireMutex(); //Retry th1 = new Thread(new ThreadStart(AcquireMutex)); th1.Start(); th1.Join(); th1=null; Console.ReadLine(); } //Test to see if it can create a mutex object static void AcquireMutex() { //Create a mutex called "vbusers.MutexTest" and don't acquire the exclusion lock. Mutex Mutex1 = new Mutex(false, "vbusers.MutexTest"); //Try and acquire the mutex exclusion lock (timeout after one second) if(Mutex1.WaitOne(1000,true)==false) { //Failed to get the lock Console.WriteLine("Thread {0}. Failed to Acquire Mutex.",AppDomain.GetCurrentThreadId()); return; } //Successfully acquired the lock Console.WriteLine("Thread {0}. Successfully Acquired Mutex.",AppDomain.GetCurrentThreadId()); //If you don't call ReleaseMutex then the mutex will only be released when the thread calling this method //terminates } } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet