воскресенье, 14 июня 2009 г.

C# 4.0 lock statement implementation

We all know what C# lock statement turns into.

Giving

static void Main(string[] args)
{
lock (s_lock)
{
}
}

We get

private static void Main(string[] args)
{
object CS$2$0000;
Monitor.Enter(CS$2$0000 = s_lock);
try
{
}
finally
{
Monitor.Exit(CS$2$0000);
}
}


But in C# 4 lock statement uses new overload of Monitor.Enter and enters guarded region inside try block.

private static void Main(string[] args)
{
object CS$2$0000;
bool <>s__LockTaken0 = false;
try
{
Monitor.Enter(CS$2$0000 = s_lock, ref <>s__LockTaken0);
}
finally
{
if (<>s__LockTaken0)
{
Monitor.Exit(CS$2$0000);
}
}
}

If you want to know what it was made for read this exhaustive Joe Duffy’s explanation.
If you have thought that the window between Monitor.Enter and try block is too short to be considered read this case.

Комментариев нет:

Отправить комментарий