Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition false, but code inside the if statement executed

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; }
        }
    }

enter image description here

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?

like image 712
Nick Avatar asked Nov 15 '25 18:11

Nick


1 Answers

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.

like image 200
albattran Avatar answered Nov 17 '25 07:11

albattran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!