I have the following method:
public bool ConnectAsync()
{
if (IsConnected)
throw new InvalidOperationException("Socket is already connected");
if (IsConnecting)
{
throw new InvalidOperationException("Attempt to connect in progress");
}
. . .
}
Where:
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; }
}
}
Why the code inside the if statement is executed if my variable isConnecting is false?
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.
Edit 2:
Finally this works:
lock (padLock)
{
if (IsConnecting)
throw new InvalidOperationException("Attempt to connect in progress");
}
And this works:
{
if (IsConnecting)
throw new InvalidOperationException("Attempt to connect in progress");
}
But why?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…