条件为false,但if语句中的代码已执行
问题描述:
我有以下方法:
public bool ConnectAsync()
{
if (IsConnected)
throw new InvalidOperationException("Socket is already connected");
if (IsConnecting)
{
throw new InvalidOperationException("Attempt to connect in progress");
}
. . .
}
其中:
private readonly object padLock = new object();
private bool isConnecting = false;
public bool IsConnected
{
get
{
lock (padLock)
{ return socket.Connected; }
}
}
public bool IsConnecting
{
get
{
lock (padLock)
{ return isConnecting; }
}
private set
{
lock (padLock)
{ isConnecting = value; }
}
}
如果我的变量isConnecting为false,为什么会执行if语句中的代码?
Why the code inside the if statement is executed if my variable isConnecting is false?
编辑:
如果我使用提交的 isConnecting
而不是属性 IsConnecting
我有相同的行为。代码在任何地方都在同一个线程中运行。
Edit:
If I use the filed isConnecting
instead of the property IsConnecting
I have the same behavior. The code runs in the same thread anywhere.
编辑2 :
最后这是有效的:
lock (padLock)
{
if (IsConnecting)
throw new InvalidOperationException("Attempt to connect in progress");
}
这样做有效:
{
if (IsConnecting)
throw new InvalidOperationException("Attempt to connect in progress");
}
但为什么?
答
调试器中的Expression窗口是触发异常的窗口,而不是代码。删除表达式(或观察),它应该按预期工作。
The Expression window you have in the debugger is the one triggering the exception, not your code. Remove expressions (or watch) and it should work as expected.