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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With