I was testing Monitor with lock taken overload as following.
public static void Enter(object obj, ref bool lockTaken);
I have created following sample for this however not sure what's the easy fix.
class TestMonitor
{
int num1 = 0;
int num2 = 0;
Random rnd = new Random();
private static object myLock = new object();
bool isLockTaken = false;
public void DoDivide()
{
try
{
Monitor.Enter(myLock, ref isLockTaken); //t2 fails here.
{
for (int i = 0; i < 5; i++)
{
num1 = rnd.Next(1, 5);
num2 = rnd.Next(1, 5);
Console.WriteLine(num1 / num2);
num1 = 0;
num2 = 0;
}
}
}
finally
{
if (isLockTaken) { Monitor.Exit(myLock); }
}
}
}
class Program
{
static void Main(string[] args)
{
Console.Title = "Monitor Demo";
TestMonitor testThreadSafe = new TestMonitor();
Thread t1 = new Thread(testThreadSafe.DoDivide);
Thread t2 = new Thread(testThreadSafe.DoDivide);
t1.Start();
t2.Start();
}
}
I am getting error when 2nd thread (t2) try to access Monitor.Enter(myLock, ref isLockTaken);
where it find that isLockTaken is true although it expects isLockTaken as false. isLockTaken is true made by 1st thread (t1) because it has obtained the lock. I kind of understood the issue but can someone points me towards easy fix so that both thread can work without issues.