Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...