如果你看看由4.0編譯器anycpu生成和反向的C#的clossest鎖equivelent實現我能得到的會是什麼樣的IL:
object x = new object();
bool lockTaken = false;
// lock
try{
System.Threading.Monitor.Enter(x, ref lockTaken)
DoSomeThing();
}
finally
{
if (lockTaken)
{
System.Threading.Monitor.Exit(x);
}
}
所有做是爲了防止在鎖被採取的情況下,一個線程中止,鎖永遠不會釋放,導致種族/僵局。警告告訴您基本上要平衡進入和退出呼叫的良好和失敗情況。鎖定語句是實現該目標的最簡單的抽象。在此基礎上IL
:
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: stloc.0
.try
{
IL_0003: ldsfld object p::x
IL_0008: dup
IL_0009: stloc.1
IL_000a: ldloca.s 0
IL_000c: call void [mscorlib]System.Threading.Monitor::Enter(object, bool&)
IL_0011: nop
IL_0012: nop
IL_0013: call void p::DoSomething()
IL_0018: nop
IL_0019: nop
IL_001a: leave.s IL_002c
} // end .try
finally
{
IL_001c: ldloc.0
IL_001d: ldc.i4.0
IL_001e: ceq
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: brtrue.s IL_002b
IL_0024: ldloc.1
IL_0025: call void [mscorlib]System.Threading.Monitor::Exit(object)
IL_002a: nop
IL_002b: endfinally
} // end handler
IL_002c: nop
IL_002d: ldsfld object p::x
IL_0032: call void [mscorlib]System.Threading.Monitor::Enter(object)
IL_0037: nop
.try
{
IL_0038: nop
IL_0039: call void p::DoSomething()
IL_003e: nop
IL_003f: nop
IL_0040: leave.s IL_0050
} // end .try
finally
{
IL_0042: nop
IL_0043: ldsfld object p::x
IL_0048: call void [mscorlib]System.Threading.Monitor::Exit(object)
IL_004d: nop
IL_004e: nop
IL_004f: endfinally
} // end handler
IL_0050: nop
IL_0051: ret
太多太好的答案。太難確定哪個標記是正確的。謝謝大家! – Fulproof 2013-02-22 14:26:53