我有以下方法:
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 语句中的代码?
编辑:
如果我使用归档isConnecting
而不是属性,IsConnecting
我有相同的行为。代码在任何地方的同一个线程中运行。
编辑 2:
最后这有效:
lock (padLock)
{
if (IsConnecting)
throw new InvalidOperationException("Attempt to connect in progress");
}
这有效:
{
if (IsConnecting)
throw new InvalidOperationException("Attempt to connect in progress");
}
但为什么?