gpt4 book ai didi

c# - 返回语句应该在锁内还是锁外?

转载 作者:IT王子 更新时间:2023-10-29 03:33:08 26 4
gpt4 key购买 nike

我刚刚意识到,在我的代码中的某些地方,我在锁内有 return 语句,有时在锁外。哪个最好?

1)

void example()
{
lock (mutex)
{
//...
}
return myData;
}

2)

void example()
{
lock (mutex)
{
//...
return myData;
}

}

我应该使用哪个?

最佳答案

本质上,无论哪种方式都会使代码更简单。单点退出是一个很好的理想,但我不会为了实现它而扭曲代码的形状......如果替代方案是声明一个局部变量(在锁外),初始化它(在锁内)和然后返回它(在锁外),然后我会说锁内的简单“return foo”要简单得多。

为了显示 IL 的差异,让我们编写代码:

static class Program
{
static void Main() { }

static readonly object sync = new object();

static int GetValue() { return 5; }

static int ReturnInside()
{
lock (sync)
{
return GetValue();
}
}

static int ReturnOutside()
{
int val;
lock (sync)
{
val = GetValue();
}
return val;
}
}

(请注意,我很乐意争辩说 ReturnInside 是 C# 的更简单/更清晰的部分)

然后查看 IL( Release模式等):

.method private hidebysig static int32 ReturnInside() cil managed
{
.maxstack 2
.locals init (
[0] int32 CS$1$0000,
[1] object CS$2$0001)
L_0000: ldsfld object Program::sync
L_0005: dup
L_0006: stloc.1
L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)
L_000c: call int32 Program::GetValue()
L_0011: stloc.0
L_0012: leave.s L_001b
L_0014: ldloc.1
L_0015: call void [mscorlib]System.Threading.Monitor::Exit(object)
L_001a: endfinally
L_001b: ldloc.0
L_001c: ret
.try L_000c to L_0014 finally handler L_0014 to L_001b
}

method private hidebysig static int32 ReturnOutside() cil managed
{
.maxstack 2
.locals init (
[0] int32 val,
[1] object CS$2$0000)
L_0000: ldsfld object Program::sync
L_0005: dup
L_0006: stloc.1
L_0007: call void [mscorlib]System.Threading.Monitor::Enter(object)
L_000c: call int32 Program::GetValue()
L_0011: stloc.0
L_0012: leave.s L_001b
L_0014: ldloc.1
L_0015: call void [mscorlib]System.Threading.Monitor::Exit(object)
L_001a: endfinally
L_001b: ldloc.0
L_001c: ret
.try L_000c to L_0014 finally handler L_0014 to L_001b
}

因此,在 IL 级别,它们 [给出或取一些名称] 相同(我学到了一些东西;-p)。因此,唯一明智的比较是本地编码风格的(高度主观的)法则......为了简单起见,我更喜欢 ReturnInside,但我不会对此感到兴奋。

关于c# - 返回语句应该在锁内还是锁外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/266681/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com