条件为假,但执行了 if 语句中的代码 [英] Condition false, but code inside the if statement executed

查看:35
本文介绍了条件为假,但执行了 if 语句中的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

public bool ConnectAsync()
{
    if (IsConnected)
        throw new InvalidOperationException("Socket is already connected");

    if (IsConnecting)
    {
        throw new InvalidOperationException("Attempt to connect in progress");
    }

    . . .
}

地点:

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

如果我的变量 isConnecting 为 false,为什么会执行 if 语句中的代码?

Why the code inside the if statement is executed if my variable isConnecting is false?

编辑:
如果我使用归档的 isConnecting 而不是属性 IsConnecting 我有相同的行为.代码在同一个线程中的任何地方运行.

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.

编辑 2:

终于可以了:

lock (padLock)
{
    if (IsConnecting)
        throw new InvalidOperationException("Attempt to connect in progress");
}

这有效:

{
    if (IsConnecting)
        throw new InvalidOperationException("Attempt to connect in progress");
}

为什么?

推荐答案

调试器中的表达式窗口是触发异常的窗口,而不是您的代码.删除表达式(或监视),它应该会按预期工作.

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 语句中的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆