I have written a small piece of code. something like below
public static void SetLicence1()
{
Console.WriteLine("Setting Aspose Licence in Thread1 ");
Console.WriteLine(SetAsposeLicense());
}
public static void SetLicence2()
{
Console.WriteLine("Setting Aspose Licence in Thread2 ");
Console.WriteLine(SetAsposeLicense());
}
public static bool SetAsposeLicense()
{
try
{
//Declare Mutex variable:
using (Mutex mutex = new System.Threading.Mutex(false, "Test"))
{
mutex.WaitOne(TimeSpan.FromSeconds(5));
var objLic = new License();
objLic.SetLicense(@"C:\Nivedita\License\Aspose.Cells.lic");
mutex.ReleaseMutex();
}
return true;
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace);
return false;
}
}
}
public class TestClass
{
public static void Main()
{
Thread tid1 = new Thread(new ThreadStart(ThreadClass.SetLicence1));
Thread tid2 = new Thread(new ThreadStart(ThreadClass.SetLicence2));
tid1.Start();
tid2.Start();
Console.Read();
}
}
This piece of code is working perfectly fine. But here my question is that is there any chance for the WaitOne() method can gets stuck in or across the processes and the mutex object doesnt get released? Although I have used mutex.ReleaseMutex().
EDIT: I've since learned this answer is incorrect. zespri explains below.
There is no chance of
mutexnot being released because it is disposed as soon as theusingblock ends. Nothing else can ever seemutexbecause it's scoped to the method. Realise that you have two, independantMutexobjects here, one in Thread1 and one in Thread2. This is simply incorrect usage ofMutex.If you need a
Mutex, try this instead:Changes:
Make
mutexa class member so that all threads can see the sameMutex.Check whether
mutexwas released, or whether it timed out.Add a nested
try/finallyblock to ensuremutexis released if setting the license throws an exception. The nesting is required becauseReleaseMetux()can only be called by the thread that successfully calledWaitOne().