Delphi and the C# lock statement
Posted: (EET/GMT+2)
If you have studied the C# language, you might be aware of the lock statement.
This is a very handy statement in multi-threaded applications. But, if you are a Delphi developed trying to hack together some example code from the net, you are at loss because Delphi doesn't support this statement.
But, since we all have a IL disassembler, it is easy to see what kind of code a C# creates when using the lock statement.
When I wrote a very simple C# application like this:
class Test
{
public static void Main()
{
System.Console.WriteLine("Before");
lock (new Test()) {
System.Console.WriteLine("Inside");
}
System.Console.WriteLine("After");
}
}
...it turned out that the generated IL code was this:
.method public hidebysig static void Main() cil managed
{
.entrypoint
// Code size 52 (0x34)
.maxstack 2
.locals init (class Test V_0)
IL_0000: ldstr "Before"
IL_0005: call void [mscorlib]System.Console::WriteLine(string)
IL_000a: newobj instance void Test::.ctor()
IL_000f: dup
IL_0010: stloc.0
IL_0011: call void [mscorlib]System.Threading.Monitor::Enter(object)
.try
{
IL_0016: ldstr "Inside"
IL_001b: call void [mscorlib]System.Console::WriteLine(string)
IL_0020: leave.s IL_0029
} // end .try
finally
{
IL_0022: ldloc.0
IL_0023: call void [mscorlib]System.Threading.Monitor::Exit(object)
IL_0028: endfinally
} // end handler
IL_0029: ldstr "After"
IL_002e: call void [mscorlib]System.Console::WriteLine(string)
IL_0033: ret
} // end of method Test::Main
So, the conclusion is that the C# lock statement uses the System.Threading.Monitor class internally.
The conclusion: if you encounted the C# lock statement in code you need to translate into Delphi code, simply use the Monitor.Enter and Monitor.Exit methods around the statement(s). And don't forget try-finally!