我可以把一个return语句里面锁 [英] Can I put a return statement inside a lock
问题描述
杜佩: 锁定程序中返回语句:内部或外部
标题是有点误导。我知道你可以做到这一点,但我想了解一下性能的影响。
The title is a little misleading. I know that you can do it, but I'm wondering about the performance implications.
考虑这些代码两个街区。 (没有错误处理)
consider these two blocks of code. (no error handling)
该模块具有收益
锁
public DownloadFile Dequeue()
{
DownloadFile toReturn = null;
lock (QueueModifierLockObject)
{
toReturn = queue[0];
queue.RemoveAt(0);
}
return toReturn;
}
该模块具有收益
声明的在的锁
public DownloadFile Dequeue()
{
lock (QueueModifierLockObject)
{
DownloadFile toReturn = queue[0];
queue.RemoveAt(0);
return toReturn;
}
}
有没有代码有什么区别?据我所知,性能差异(如有)将是最小的,但我特别想知道是否会有顺序的锁定
得到释放差异。
推荐答案
C#编译器将移动return语句尝试/终于
的外是锁定
语句创建的。 。您的两个例子是相同的IL而言,编译器将发出他们
The C# compiler will move the return statement outside of the try/finally
that is created for the lock
statement. Both of your examples are identical in terms of the IL that the compiler will emit for them.
下面是一个简单的例子证明:
Here is a simple example proving that:
class Example
{
static Object obj = new Object();
static int Foo()
{
lock (obj)
{
Console.WriteLine("Foo");
return 1;
}
}
static int Bar()
{
lock (obj)
{
Console.WriteLine("Bar");
}
return 2;
}
}
上面的代码被编译为以下内容:
The code above gets compiled to the following:
internal class Example
{
private static object obj;
static Example()
{
obj = new object();
return;
}
public Example()
{
base..ctor();
return;
}
private static int Bar()
{
int CS$1$0000;
object CS$2$0001;
Monitor.Enter(CS$2$0001 = obj);
Label_000E:
try
{
Console.WriteLine("Bar");
goto Label_0025;
}
finally
{
Label_001D:
Monitor.Exit(CS$2$0001);
}
Label_0025:
CS$1$0000 = 2;
Label_002A:
return CS$1$0000;
}
private static int Foo()
{
int CS$1$0000;
object CS$2$0001;
Monitor.Enter(CS$2$0001 = obj);
Label_000E:
try
{
Console.WriteLine("Foo");
CS$1$0000 = 1;
goto Label_0026;
}
finally
{
Label_001E:
Monitor.Exit(CS$2$0001);
}
Label_0026:
return CS$1$0000;
}
}
正如你所看到的,编译器采取了libery在富
移动return语句尝试/终于
。
As you can see, the compiler has taken the libery of moving the return statement in Foo
outside of the try/finally
.
这篇关于我可以把一个return语句里面锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!