R
Russell Stuart via .NET 247
I always though .Net monitors were meant to be similar to thejava synchronisation mechanisms. The code below proves mewrong. When run under the debugger, it produces just "Thread 1"lines, as I expected. But when run without the debugger itproduced both "Thread 1" and "Thread 2" lines, impling that twothreads are executing in the same lock region. I though thatwasn't supposed to happen. Am I wrong?
using System;
using System.Threading;
public class Test
{
Thread t1, t2;
public void Run1()
{
Thread.Sleep(1000);
lock (this)
{
Monitor.Pulse(this);
t2.Interrupt();
for (;
Console.WriteLine("Thread 1");
}
}
public void Run2()
{
lock (this)
{
try
{
Monitor.Wait(this);
}
catch (ThreadInterruptedException)
{
Console.WriteLine("2 Interrupted");
}
for (;
Console.WriteLine("Thread 2");
}
}
public void Go()
{
t1 = new Thread(new ThreadStart(Run1));
t2 = new Thread(new ThreadStart(Run2));
t1.Start();
t2.Start();
}
public static void Main()
{
new Test().Go();
}
}
using System;
using System.Threading;
public class Test
{
Thread t1, t2;
public void Run1()
{
Thread.Sleep(1000);
lock (this)
{
Monitor.Pulse(this);
t2.Interrupt();
for (;
Console.WriteLine("Thread 1");
}
}
public void Run2()
{
lock (this)
{
try
{
Monitor.Wait(this);
}
catch (ThreadInterruptedException)
{
Console.WriteLine("2 Interrupted");
}
for (;
Console.WriteLine("Thread 2");
}
}
public void Go()
{
t1 = new Thread(new ThreadStart(Run1));
t2 = new Thread(new ThreadStart(Run2));
t1.Start();
t2.Start();
}
public static void Main()
{
new Test().Go();
}
}