以下程序打印:
Entered 3
Entered 4
Wait for Exited messages
Exited 3
Exited 4
意味着它无法获取资源的独占锁。为什么呢?
public class Worker
{
public void DoIt(object resource)
{
Monitor.Enter(resource);
Console.WriteLine("Entered " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(3000);
Monitor.Exit(resource);
Console.WriteLine("Exited " + Thread.CurrentThread.ManagedThreadId);
}
}
class Program
{
struct Resource
{
public int A;
public int B;
}
static void Main(string[] args)
{
Resource resource;
resource.A = 0;
resource.B = 1;
var a = new Worker();
var b = new Worker();
var t1 = new Thread(() => a.DoIt(resource));
var t2 = new Thread(() => b.DoIt(resource));
t1.Start();
t2.Start();
Console.WriteLine("Wait for Exited messages");
Console.ReadLine();
}
}
答案 0 :(得分:10)
您的Resource
是一个结构。它传递给DoIt
时会被装箱,因此每次调用DoIt
都会锁定一个不同的对象。将Resource
更改为班级。