简体   繁体   English

条件为假,但执行了 if 语句中的代码

[英]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; }
        }
    }

在此处输入图像描述

Why the code inside the if statement is executed if my variable isConnecting is false?如果我的变量 isConnecting 为假,为什么执行 if 语句中的代码?

Edit :编辑
If I use the filed isConnecting instead of the property IsConnecting I have the same behavior.如果我使用归档的isConnecting而不是属性IsConnecting我有相同的行为。 The code runs in the same thread anywhere.代码在任何地方都在同一个线程中运行。

Edit 2 :编辑 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?但为什么?

这可能是调试器和多个线程的问题,尝试将锁定放在if语句的外部而不是属性内部。

The Expression window you have in the debugger is the one triggering the exception, not your code. 调试器中的Expression窗口是触发异常的窗口,而不是代码。 Remove expressions (or watch) and it should work as expected. 删除表达式(或观察),它应该按预期工作。

This answer explained the problem I was having: https://stackoverflow.com/a/27552124/1830461 这个答案解释了我遇到的问题: https//stackoverflow.com/a/27552124/1830461

Something of this format compiled to 64-bit can cause the debugger to step into the if statement: 将此格式的某些内容编译为64位可能会导致调试器进入if语句:

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

It's a bug in Visual Studio. 这是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. 在其上放置一个锁定语句会修复它,因为它不再是那种格式。

I experienced this when I was debugging my code whilst the configuration mode was Release .我在调试代码时遇到过这种情况,而配置模式是Release

Simply setting the configuration mode to Debug resolved the issue.只需将配置模式设置为Debug即可解决问题。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM