Nick
Nick

Reputation: 10499

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?

Upvotes: 4

Views: 6120

Answers (4)

YungDeiza
YungDeiza

Reputation: 4530

I experienced this when I was debugging my code whilst the configuration mode was Release.

Simply setting the configuration mode to Debug resolved the issue.

enter image description here

Upvotes: 0

bcwhims
bcwhims

Reputation: 2875

This answer explained the problem I was having: https://stackoverflow.com/a/27552124/1830461

Something of this format compiled to 64-bit can cause the debugger to step into the if statement:

        if (falseCondition) 
            throw new Exception(); 
        try { }  catch { }

It's a bug in Visual Studio. The code isn't actually executed. The solution is to just ignore it and continue stepping through the code. Putting a lock statement on it fixes it, because it is no longer in that format.

Upvotes: 1

albattran
albattran

Reputation: 1907

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.

Upvotes: 4

gmn
gmn

Reputation: 4319

This is probably an issue with the debugger and multiple threads, try putting the lock around the outside of the if statement rather than inside the property.

Upvotes: 4

Related Questions